AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/10/16 23:00 flow patch-triage
8m Args:
null

Results:
{
  "EnableConfigs": [
    "KVM",
    "KVM_INTEL",
    "KVM_AMD",
    "KVM_XEN"
  ],
  "FocusSymbols": [
    "kvm_gpc_refresh",
    "kvm_gpc_activate",
    "kvm_xen_hvm_set_attr",
    "kvm_xen_vcpu_set_attr",
    "kvm_xen_vcpu_get_attr",
    "kvm_xen_hypercall",
    "kvm_xen_hvm_evtchn_send",
    "kvm_xen_set_evtchn_fast",
    "kvm_xen_inject_timer_irqs",
    "kvm_xen_write_hypercall_page"
  ],
  "KMSANReasoning": "The patch series addresses deadlock and race conditions between KVM memslot updates and Xen emulation (specifically gfn_to_pfn_cache) when executed within SRCU read sections. The main modifications include:\n1. Introducing an -EAGAIN return when a memslot is transiently invalid (under churn) and adding a retry loop with a `wait` parameter to `kvm_gpc_activate()` and `kvm_gpc_refresh()`.\n2. Restructuring lock nesting around `xen_lock` and GPC read locks to ensure that memslot waits do not hold locks that could deadlock against SRCU readers.\n3. Deferring guest TLB flush requests (`KVM_REQ_TLB_FLUSH_GUEST`) during `record_steal_time()` and handling them on guest entry.\n4. Adding a `never_dirty` flag to `struct gfn_to_pfn_cache` to skip dirty page logging for Xen shared_info and vcpu_info.\n\nNone of these changes introduce or modify uninitialized memory access risks:\n- All new struct fields (`gpc-\u003enever_dirty`) and local variables (`inject_upcall`, `kick_vcpu`, `wait`, `rc`, etc.) are explicitly initialized before use.\n- No kernel-to-user memory transfers are modified in a way that risks uninitialized data or padding leaks (`kvm_xen_vcpu_get_attr` operates on an `xva` buffer populated by `copy_from_user`).\n- The hazards associated with this patch involve lock ordering, deadlocks, and race conditions during concurrent memslot updates and Xen event delivery. These are monitored by LOCKDEP and standard KASAN configurations. KMSAN does not provide additional detection capability here.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch series refactors locking, synchronization, and race handling between memslot updates and gfn_to_pfn_cache (GPC) operations in KVM, specifically focusing on KVM Xen emulation (such as event channel delivery, timer IRQ injection, and hypercall handling racing against memslot deletion). These changes touch core reachable virtualization logic in virt/kvm/pfncache.c and arch/x86/kvm/xen.c, which are exercisable via /dev/kvm ioctls and guest hypercalls in standard virtualized environments. Because of the subtle concurrency semantics, lockdep assertions, and state management changes, this patch series warrants fuzzing.",
  "WorthFuzzing": true
}

1/1 2026/10/16 23:00 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit d8614fa8ccb8870dac5d746557f59a5d34989939\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Fri Oct 16 23:00:39 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..ed633a39a97a2 100644\n--- a/arch/x86/include/asm/kvm_host.h\n+++ b/arch/x86/include/asm/kvm_host.h\n@@ -1108,6 +1108,12 @@ struct kvm_hv {\n #ifdef CONFIG_KVM_XEN\n /* Xen emulation context */\n struct kvm_xen {\n+\t/*\n+\t * Taken from within kvm-\u003esrcu read sections (e.g. by a vCPU\n+\t * writing the hypercall page MSR), so never held while waiting\n+\t * out a memslot update: the update waits for those read\n+\t * sections to quiesce.\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..82adc5741f8db 100644\n--- a/arch/x86/kvm/xen.c\n+++ b/arch/x86/kvm/xen.c\n@@ -30,13 +30,27 @@\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 inline int max_evtchn_port(bool has_64bit_shinfo)\n+{\n+\tif (has_64bit_shinfo)\n+\t\treturn EVTCHN_2L_NR_CHANNELS;\n+\telse\n+\t\treturn COMPAT_EVTCHN_2L_NR_CHANNELS;\n+}\n+\n+static inline int kvm_max_evtchn_port(struct kvm *kvm)\n+{\n+\treturn max_evtchn_port(kvm_xen_has_64bit_shinfo(kvm));\n+}\n+\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 +58,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 +119,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 +129,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@@ -155,21 +198,29 @@ static int xen_get_guest_pvclock(struct kvm_vcpu *vcpu,\n \t\t\t\t unsigned int offset)\n {\n \tunsigned long flags;\n-\tint r;\n+\tint idx, r;\n \n-\tread_lock_irqsave(\u0026gpc-\u003elock, flags);\n-\twhile (!kvm_gpc_check(gpc, offset + sizeof(*hv_clock))) {\n+\t/*\n+\t * As in kvm_xen_shared_info_init(): kvm_gpc_check() consults the\n+\t * memslots, so take kvm-\u003esrcu around each check and the copy, but\n+\t * not across the refresh.\n+\t */\n+\tfor (;;) {\n+\t\tidx = srcu_read_lock(\u0026vcpu-\u003ekvm-\u003esrcu);\n+\t\tread_lock_irqsave(\u0026gpc-\u003elock, flags);\n+\t\tif (kvm_gpc_check(gpc, offset + sizeof(*hv_clock)))\n+\t\t\tbreak;\n \t\tread_unlock_irqrestore(\u0026gpc-\u003elock, flags);\n+\t\tsrcu_read_unlock(\u0026vcpu-\u003ekvm-\u003esrcu, idx);\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-\t\tread_lock_irqsave(\u0026gpc-\u003elock, flags);\n \t}\n \n \tmemcpy(hv_clock, gpc-\u003ekhva + offset, sizeof(*hv_clock));\n \tread_unlock_irqrestore(\u0026gpc-\u003elock, flags);\n+\tsrcu_read_unlock(\u0026vcpu-\u003ekvm-\u003esrcu, idx);\n \n \t/*\n \t * Sanity check TSC shift+multiplier to verify the guest's view of time\n@@ -435,7 +486,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 +539,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 +720,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 +756,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 +807,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@@ -784,27 +834,34 @@ int kvm_xen_hvm_set_attr(struct kvm *kvm, struct kvm_xen_hvm_attr *data)\n \t\t} else {\n \t\t\tmutex_lock(\u0026kvm-\u003earch.xen.xen_lock);\n \t\t\tkvm-\u003earch.xen.long_mode = !!data-\u003eu.long_mode;\n+\t\t\tmutex_unlock(\u0026kvm-\u003earch.xen.xen_lock);\n \n \t\t\t/*\n \t\t\t * Re-initialize shared_info to put the wallclock in the\n \t\t\t * correct place. Whilst it's not necessary to do this\n \t\t\t * unless the mode is actually changed, it does no harm\n-\t\t\t * to make the call anyway.\n+\t\t\t * to make the call anyway. Done without xen_lock held:\n+\t\t\t * the init may wait out a memslot update, and a vCPU\n+\t\t\t * may block on xen_lock from within the kvm-\u003esrcu read\n+\t\t\t * section which that update must wait out.\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\tmutex_unlock(\u0026kvm-\u003earch.xen.xen_lock);\n+\t\t\t\tkvm_xen_shared_info_init(kvm, true) : 0;\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\t/*\n+\t\t * Deactivation stays under xen_lock, but an activation may\n+\t\t * wait out a memslot update and so must not hold it: a vCPU\n+\t\t * may block on xen_lock from within the kvm-\u003esrcu read\n+\t\t * section which that update must wait out. Concurrent\n+\t\t * SET_ATTR calls racing in the window are userspace's own\n+\t\t * race; the cache layer serializes them, last one wins.\n+\t\t */\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@@ -812,8 +869,10 @@ int kvm_xen_hvm_set_attr(struct kvm *kvm, struct kvm_xen_hvm_attr *data)\n \t\t\t\tkvm_gpc_deactivate(\u0026kvm-\u003earch.xen.shinfo_cache);\n \t\t\t\tr = 0;\n \t\t\t} else {\n+\t\t\t\tmutex_unlock(\u0026kvm-\u003earch.xen.xen_lock);\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\tmutex_lock(\u0026kvm-\u003earch.xen.xen_lock);\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,12 +888,11 @@ 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+\t\tmutex_unlock(\u0026kvm-\u003earch.xen.xen_lock);\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 \t}\n \tcase KVM_XEN_ATTR_TYPE_UPCALL_VECTOR:\n@@ -937,7 +995,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@@ -959,8 +1016,16 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)\n \t\t\tif (!IS_ALIGNED(data-\u003eu.gpa, sizeof(u32)))\n \t\t\t\tbreak;\n \n+\t\t\t/*\n+\t\t\t * As with the shared_info attributes: a waiting\n+\t\t\t * activation must not hold xen_lock, on which a\n+\t\t\t * vCPU may block from within the kvm-\u003esrcu read\n+\t\t\t * section the memslot update has to wait out.\n+\t\t\t */\n+\t\t\tmutex_unlock(\u0026vcpu-\u003ekvm-\u003earch.xen.xen_lock);\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\tmutex_lock(\u0026vcpu-\u003ekvm-\u003earch.xen.xen_lock);\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@@ -988,9 +1053,11 @@ 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\tmutex_unlock(\u0026vcpu-\u003ekvm-\u003earch.xen.xen_lock);\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\tmutex_lock(\u0026vcpu-\u003ekvm-\u003earch.xen.xen_lock);\n \t\tif (!r)\n \t\t\tkvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);\n \t\tbreak;\n@@ -1022,10 +1089,14 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)\n \n \t\t/* How much fits in the (first) page? */\n \t\tsz1 = PAGE_SIZE - (data-\u003eu.gpa \u0026 ~PAGE_MASK);\n+\n+\t\tmutex_unlock(\u0026vcpu-\u003ekvm-\u003earch.xen.xen_lock);\n \t\tr = kvm_gpc_activate(\u0026vcpu-\u003earch.xen.runstate_cache,\n-\t\t\t\t     data-\u003eu.gpa, sz1);\n-\t\tif (r)\n+\t\t\t\t     data-\u003eu.gpa, sz1, true);\n+\t\tif (r) {\n+\t\t\tmutex_lock(\u0026vcpu-\u003ekvm-\u003earch.xen.xen_lock);\n \t\t\tgoto deactivate_out;\n+\t\t}\n \n \t\t/* Either map the second page, or deactivate the second GPC */\n \t\tif (sz1 \u003e= sz) {\n@@ -1034,12 +1105,17 @@ 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\tif (r)\n+\t\t\t\t\t     data-\u003eu.gpa + sz1, sz2, true);\n+\t\t\tif (r) {\n+\t\t\t\tmutex_lock(\u0026vcpu-\u003ekvm-\u003earch.xen.xen_lock);\n \t\t\t\tgoto deactivate_out;\n+\t\t\t}\n \t\t}\n+\t\tmutex_lock(\u0026vcpu-\u003ekvm-\u003earch.xen.xen_lock);\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 +1128,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 +1210,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 +1261,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,13 +1346,14 @@ 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 * timer_pending flag) and there is no need to cancel it.\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 as an optimisation, if the\n+\t\t * timer_expires field is zero, that means the timer isn't\n+\t\t * active (or even in the timer_pending flag) and there is\n+\t\t * no need to cancel it.\n \t\t */\n \t\tif (vcpu-\u003earch.xen.timer_expires) {\n \t\t\thrtimer_cancel(\u0026vcpu-\u003earch.xen.timer);\n@@ -1291,10 +1371,27 @@ 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\t * Don't re-arm an undeliverable port: the immediate fire\n+\t\t * would get -EINVAL from the delivery path and destroy\n+\t\t * the timer_expires state just reported to userspace.\n \t\t */\n-\t\tif (vcpu-\u003earch.xen.timer_expires)\n-\t\t\thrtimer_start_expires(\u0026vcpu-\u003earch.xen.timer,\n-\t\t\t\t\t      HRTIMER_MODE_ABS_HARD);\n+\t\tif (vcpu-\u003earch.xen.timer_expires \u0026\u0026\n+\t\t    !atomic_read(\u0026vcpu-\u003earch.xen.timer_pending) \u0026\u0026\n+\t\t    vcpu-\u003earch.xen.timer_virq \u003c kvm_max_evtchn_port(vcpu-\u003ekvm))\n+\t\t\tkvm_xen_start_timer(vcpu, vcpu-\u003earch.xen.timer_expires,\n+\t\t\t\t\t    false);\n \n \t\tr = 0;\n \t\tbreak;\n@@ -1326,11 +1423,20 @@ int kvm_xen_write_hypercall_page(struct kvm_vcpu *vcpu, u64 data)\n \n \t\t/*\n \t\t * Re-initialize shared_info to put the wallclock in the\n-\t\t * correct place.\n+\t\t * correct place. The wallclock is a snapshot, written only\n+\t\t * here, and this cannot wait out a memslot update from\n+\t\t * within the vCPU's kvm-\u003esrcu read section. If it races\n+\t\t * one (-EAGAIN), just proceed with the stale snapshot; a\n+\t\t * guest changing its own bitness while userspace is\n+\t\t * rearranging memslots has only itself to blame. A real\n+\t\t * failure still fails the WRMSR as it always did.\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\tr = 1;\n+\t\tif (kvm-\u003earch.xen.shinfo_cache.active) {\n+\t\t\tint ret = kvm_xen_shared_info_init(kvm, false);\n+\n+\t\t\tif (ret \u0026\u0026 ret != -EAGAIN)\n+\t\t\t\tr = 1;\n+\t\t}\n \t}\n \tmutex_unlock(\u0026kvm-\u003earch.xen.xen_lock);\n \n@@ -1461,19 +1567,6 @@ static int kvm_xen_hypercall_complete_userspace(struct kvm_vcpu *vcpu)\n \treturn kvm_xen_hypercall_set_result(vcpu, run-\u003exen.u.hcall.result);\n }\n \n-static inline int max_evtchn_port(bool has_64bit_shinfo)\n-{\n-\tif (has_64bit_shinfo)\n-\t\treturn EVTCHN_2L_NR_CHANNELS;\n-\telse\n-\t\treturn COMPAT_EVTCHN_2L_NR_CHANNELS;\n-}\n-\n-static inline int kvm_max_evtchn_port(struct kvm *kvm)\n-{\n-\treturn max_evtchn_port(kvm_xen_has_64bit_shinfo(kvm));\n-}\n-\n static bool wait_pending_event(struct kvm_vcpu *vcpu, bool has_64bit_shinfo,\n \t\t\t       int nr_ports, evtchn_port_t *ports)\n {\n@@ -1775,8 +1868,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 +1937,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 +2034,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 +2059,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 +2087,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 +2147,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 +2168,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 +2242,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 +2471,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 +2485,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 +2494,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 +2523,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 +2544,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..ba23f4e0a4c0f 100644\n--- a/include/linux/kvm_host.h\n+++ b/include/linux/kvm_host.h\n@@ -1456,16 +1456,23 @@ int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,\n \t\t\t unsigned long len);\n \n /**\n- * kvm_gpc_init - initialize gfn_to_pfn_cache.\n+ * __kvm_gpc_init - initialize gfn_to_pfn_cache.\n  *\n  * @gpc:\t   struct gfn_to_pfn_cache object.\n  * @kvm:\t   pointer to kvm instance.\n+ * @never_dirty:   the cache never needs to mark its page dirty in its memslot.\n  *\n  * This sets up a gfn_to_pfn_cache by initializing locks and assigning the\n  * immutable attributes.  Note, the cache must be zero-allocated (or zeroed by\n- * the caller before init).\n+ * the caller before init).  Most callers want the kvm_gpc_init() wrapper.\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 +1481,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@@ -1496,10 +1511,13 @@ int kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long len)\n  *                -EINVAL for a mapping which would cross a page boundary.\n  *                -EFAULT for an untranslatable guest physical address.\n  *\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+ * The semantics of this function are the same as those of kvm_gpc_activate(),\n+ * except that an HVA-based cache never consults the memslots and so can\n+ * neither return -EAGAIN nor wait: it merely bypasses a layer of address\n+ * 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 +1542,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 +1556,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 +1997,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..729c0ba9ab4e8 100644\n--- a/tools/testing/selftests/kvm/x86/xen_shinfo_test.c\n+++ b/tools/testing/selftests/kvm/x86/xen_shinfo_test.c\n@@ -350,17 +350,25 @@ static void guest_code(void)\n \tp = (struct sched_poll) {\n \t\t.ports = ports,\n \t\t.nr_ports = 1,\n-\t\t.timeout = 0\n+\t\t/*\n+\t\t * The poll must have a timeout: if the timer event is dropped\n+\t\t * while we are already blocked in the poll, nothing else will\n+\t\t * ever wake us, and the recovery protocol below could never\n+\t\t * run. (As with TEST_POLL_TIMEOUT above, KVM treats the\n+\t\t * timeout as relative.)\n+\t\t */\n+\t\t.timeout = 10000000,\n \t};\n \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/16 23:00 agent patch-evaluator
5m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "KVM",
    "KVM_INTEL",
    "KVM_AMD",
    "KVM_XEN"
  ],
  "FocusSymbols": [
    "kvm_gpc_refresh",
    "kvm_gpc_activate",
    "kvm_xen_hvm_set_attr",
    "kvm_xen_vcpu_set_attr",
    "kvm_xen_vcpu_get_attr",
    "kvm_xen_hypercall",
    "kvm_xen_hvm_evtchn_send",
    "kvm_xen_set_evtchn_fast",
    "kvm_xen_inject_timer_irqs",
    "kvm_xen_write_hypercall_page"
  ],
  "Reasoning": "The patch series refactors locking, synchronization, and race handling between memslot updates and gfn_to_pfn_cache (GPC) operations in KVM, specifically focusing on KVM Xen emulation (such as event channel delivery, timer IRQ injection, and hypercall handling racing against memslot deletion). These changes touch core reachable virtualization logic in virt/kvm/pfncache.c and arch/x86/kvm/xen.c, which are exercisable via /dev/kvm ioctls and guest hypercalls in standard virtualized environments. Because of the subtle concurrency semantics, lockdep assertions, and state management changes, this patch series warrants fuzzing.",
  "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 d8614fa8ccb8870dac5d746557f59a5d34989939
Author: syz-cluster <triage@syzkaller.com>
Date:   Fri Oct 16 23:00:39 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..ed633a39a97a2 100644
--- a/arch/x86/include/asm/kvm_host.h
+++ b/arch/x86/include/asm/kvm_host.h
@@ -1108,6 +1108,12 @@ struct kvm_hv {
 #ifdef CONFIG_KVM_XEN
 /* Xen emulation context */
 struct kvm_xen {
+	/*
+	 * Taken from within kvm->srcu read sections (e.g. by a vCPU
+	 * writing the hypercall page MSR), so never held while waiting
+	 * out a memslot update: the update waits for those read
+	 * sections to quiesce.
+	 */
 	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..82adc5741f8db 100644
--- a/arch/x86/kvm/xen.c
+++ b/arch/x86/kvm/xen.c
@@ -30,13 +30,27 @@
 #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 inline int max_evtchn_port(bool has_64bit_shinfo)
+{
+	if (has_64bit_shinfo)
+		return EVTCHN_2L_NR_CHANNELS;
+	else
+		return COMPAT_EVTCHN_2L_NR_CHANNELS;
+}
+
+static inline int kvm_max_evtchn_port(struct kvm *kvm)
+{
+	return max_evtchn_port(kvm_xen_has_64bit_shinfo(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 +58,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 +119,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 +129,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);
@@ -155,21 +198,29 @@ static int xen_get_guest_pvclock(struct kvm_vcpu *vcpu,
 				 unsigned int offset)
 {
 	unsigned long flags;
-	int r;
+	int idx, r;
 
-	read_lock_irqsave(&gpc->lock, flags);
-	while (!kvm_gpc_check(gpc, offset + sizeof(*hv_clock))) {
+	/*
+	 * As in kvm_xen_shared_info_init(): kvm_gpc_check() consults the
+	 * memslots, so take kvm->srcu around each check and the copy, but
+	 * not across the refresh.
+	 */
+	for (;;) {
+		idx = srcu_read_lock(&vcpu->kvm->srcu);
+		read_lock_irqsave(&gpc->lock, flags);
+		if (kvm_gpc_check(gpc, offset + sizeof(*hv_clock)))
+			break;
 		read_unlock_irqrestore(&gpc->lock, flags);
+		srcu_read_unlock(&vcpu->kvm->srcu, idx);
 
-		r = kvm_gpc_refresh(gpc, offset + sizeof(*hv_clock));
+		r = kvm_gpc_refresh(gpc, offset + sizeof(*hv_clock), false);
 		if (r)
 			return r;
-
-		read_lock_irqsave(&gpc->lock, flags);
 	}
 
 	memcpy(hv_clock, gpc->khva + offset, sizeof(*hv_clock));
 	read_unlock_irqrestore(&gpc->lock, flags);
+	srcu_read_unlock(&vcpu->kvm->srcu, idx);
 
 	/*
 	 * Sanity check TSC shift+multiplier to verify the guest's view of time
@@ -435,7 +486,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 +539,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 +720,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 +756,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 +807,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.
@@ -784,27 +834,34 @@ int kvm_xen_hvm_set_attr(struct kvm *kvm, struct kvm_xen_hvm_attr *data)
 		} else {
 			mutex_lock(&kvm->arch.xen.xen_lock);
 			kvm->arch.xen.long_mode = !!data->u.long_mode;
+			mutex_unlock(&kvm->arch.xen.xen_lock);
 
 			/*
 			 * Re-initialize shared_info to put the wallclock in the
 			 * correct place. Whilst it's not necessary to do this
 			 * unless the mode is actually changed, it does no harm
-			 * to make the call anyway.
+			 * to make the call anyway. Done without xen_lock held:
+			 * the init may wait out a memslot update, and a vCPU
+			 * may block on xen_lock from within the kvm->srcu read
+			 * section which that update must wait out.
 			 */
 			r = kvm->arch.xen.shinfo_cache.active ?
-				kvm_xen_shared_info_init(kvm) : 0;
-			mutex_unlock(&kvm->arch.xen.xen_lock);
+				kvm_xen_shared_info_init(kvm, true) : 0;
 		}
 		break;
 
 	case KVM_XEN_ATTR_TYPE_SHARED_INFO:
 	case KVM_XEN_ATTR_TYPE_SHARED_INFO_HVA: {
-		int idx;
-
+		/*
+		 * Deactivation stays under xen_lock, but an activation may
+		 * wait out a memslot update and so must not hold it: a vCPU
+		 * may block on xen_lock from within the kvm->srcu read
+		 * section which that update must wait out. Concurrent
+		 * SET_ATTR calls racing in the window are userspace's own
+		 * race; the cache layer serializes them, last one wins.
+		 */
 		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;
 
@@ -812,8 +869,10 @@ int kvm_xen_hvm_set_attr(struct kvm *kvm, struct kvm_xen_hvm_attr *data)
 				kvm_gpc_deactivate(&kvm->arch.xen.shinfo_cache);
 				r = 0;
 			} else {
+				mutex_unlock(&kvm->arch.xen.xen_lock);
 				r = kvm_gpc_activate(&kvm->arch.xen.shinfo_cache,
-						     gfn_to_gpa(gfn), PAGE_SIZE);
+						     gfn_to_gpa(gfn), PAGE_SIZE, true);
+				mutex_lock(&kvm->arch.xen.xen_lock);
 			}
 		} else {
 			void __user * hva = u64_to_user_ptr(data->u.shared_info.hva);
@@ -829,12 +888,11 @@ int kvm_xen_hvm_set_attr(struct kvm *kvm, struct kvm_xen_hvm_attr *data)
 			}
 		}
 
-		srcu_read_unlock(&kvm->srcu, idx);
+		mutex_unlock(&kvm->arch.xen.xen_lock);
 
 		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;
 	}
 	case KVM_XEN_ATTR_TYPE_UPCALL_VECTOR:
@@ -937,7 +995,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:
@@ -959,8 +1016,16 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
 			if (!IS_ALIGNED(data->u.gpa, sizeof(u32)))
 				break;
 
+			/*
+			 * As with the shared_info attributes: a waiting
+			 * activation must not hold xen_lock, on which a
+			 * vCPU may block from within the kvm->srcu read
+			 * section the memslot update has to wait out.
+			 */
+			mutex_unlock(&vcpu->kvm->arch.xen.xen_lock);
 			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);
+			mutex_lock(&vcpu->kvm->arch.xen.xen_lock);
 		} else {
 			if (data->u.hva == 0) {
 				kvm_gpc_deactivate(&vcpu->arch.xen.vcpu_info_cache);
@@ -988,9 +1053,11 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
 			break;
 		}
 
+		mutex_unlock(&vcpu->kvm->arch.xen.xen_lock);
 		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);
+		mutex_lock(&vcpu->kvm->arch.xen.xen_lock);
 		if (!r)
 			kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
 		break;
@@ -1022,10 +1089,14 @@ 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);
+
+		mutex_unlock(&vcpu->kvm->arch.xen.xen_lock);
 		r = kvm_gpc_activate(&vcpu->arch.xen.runstate_cache,
-				     data->u.gpa, sz1);
-		if (r)
+				     data->u.gpa, sz1, true);
+		if (r) {
+			mutex_lock(&vcpu->kvm->arch.xen.xen_lock);
 			goto deactivate_out;
+		}
 
 		/* Either map the second page, or deactivate the second GPC */
 		if (sz1 >= sz) {
@@ -1034,12 +1105,17 @@ 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);
-			if (r)
+					     data->u.gpa + sz1, sz2, true);
+			if (r) {
+				mutex_lock(&vcpu->kvm->arch.xen.xen_lock);
 				goto deactivate_out;
+			}
 		}
+		mutex_lock(&vcpu->kvm->arch.xen.xen_lock);
 
+		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 +1128,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 +1210,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 +1261,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,13 +1346,14 @@ 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
-		 * timer_pending flag) and there is no need to cancel it.
+		 * 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) {
 			hrtimer_cancel(&vcpu->arch.xen.timer);
@@ -1291,10 +1371,27 @@ 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.
+		 *
+		 * Don't re-arm an undeliverable port: the immediate fire
+		 * would get -EINVAL from the delivery path and destroy
+		 * the timer_expires state just reported to userspace.
 		 */
-		if (vcpu->arch.xen.timer_expires)
-			hrtimer_start_expires(&vcpu->arch.xen.timer,
-					      HRTIMER_MODE_ABS_HARD);
+		if (vcpu->arch.xen.timer_expires &&
+		    !atomic_read(&vcpu->arch.xen.timer_pending) &&
+		    vcpu->arch.xen.timer_virq < kvm_max_evtchn_port(vcpu->kvm))
+			kvm_xen_start_timer(vcpu, vcpu->arch.xen.timer_expires,
+					    false);
 
 		r = 0;
 		break;
@@ -1326,11 +1423,20 @@ int kvm_xen_write_hypercall_page(struct kvm_vcpu *vcpu, u64 data)
 
 		/*
 		 * Re-initialize shared_info to put the wallclock in the
-		 * correct place.
+		 * correct place. The wallclock is a snapshot, written only
+		 * here, and this cannot wait out a memslot update from
+		 * within the vCPU's kvm->srcu read section. If it races
+		 * one (-EAGAIN), just proceed with the stale snapshot; a
+		 * guest changing its own bitness while userspace is
+		 * rearranging memslots has only itself to blame. A real
+		 * failure still fails the WRMSR as it always did.
 		 */
-		if (kvm->arch.xen.shinfo_cache.active &&
-		    kvm_xen_shared_info_init(kvm))
-			r = 1;
+		if (kvm->arch.xen.shinfo_cache.active) {
+			int ret = kvm_xen_shared_info_init(kvm, false);
+
+			if (ret && ret != -EAGAIN)
+				r = 1;
+		}
 	}
 	mutex_unlock(&kvm->arch.xen.xen_lock);
 
@@ -1461,19 +1567,6 @@ static int kvm_xen_hypercall_complete_userspace(struct kvm_vcpu *vcpu)
 	return kvm_xen_hypercall_set_result(vcpu, run->xen.u.hcall.result);
 }
 
-static inline int max_evtchn_port(bool has_64bit_shinfo)
-{
-	if (has_64bit_shinfo)
-		return EVTCHN_2L_NR_CHANNELS;
-	else
-		return COMPAT_EVTCHN_2L_NR_CHANNELS;
-}
-
-static inline int kvm_max_evtchn_port(struct kvm *kvm)
-{
-	return max_evtchn_port(kvm_xen_has_64bit_shinfo(kvm));
-}
-
 static bool wait_pending_event(struct kvm_vcpu *vcpu, bool has_64bit_shinfo,
 			       int nr_ports, evtchn_port_t *ports)
 {
@@ -1775,8 +1868,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 +1937,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 +2034,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 +2059,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 +2087,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 +2147,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 +2168,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 +2242,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 +2471,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 +2485,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 +2494,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 +2523,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 +2544,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..ba23f4e0a4c0f 100644
--- a/include/linux/kvm_host.h
+++ b/include/linux/kvm_host.h
@@ -1456,16 +1456,23 @@ int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
 			 unsigned long len);
 
 /**
- * kvm_gpc_init - initialize gfn_to_pfn_cache.
+ * __kvm_gpc_init - initialize gfn_to_pfn_cache.
  *
  * @gpc:	   struct gfn_to_pfn_cache object.
  * @kvm:	   pointer to kvm instance.
+ * @never_dirty:   the cache never needs to mark its page dirty in its memslot.
  *
  * This sets up a gfn_to_pfn_cache by initializing locks and assigning the
  * immutable attributes.  Note, the cache must be zero-allocated (or zeroed by
- * the caller before init).
+ * the caller before init).  Most callers want the kvm_gpc_init() wrapper.
  */
-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 +1481,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.
@@ -1496,10 +1511,13 @@ int kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long len)
  *                -EINVAL for a mapping which would cross a page boundary.
  *                -EFAULT for an untranslatable guest physical address.
  *
- * The semantics of this function are the same as those of kvm_gpc_activate(). It
- * merely bypasses a layer of address translation.
+ * The semantics of this function are the same as those of kvm_gpc_activate(),
+ * except that an HVA-based cache never consults the memslots and so can
+ * neither return -EAGAIN nor wait: 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 +1542,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 +1556,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 +1997,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..729c0ba9ab4e8 100644
--- a/tools/testing/selftests/kvm/x86/xen_shinfo_test.c
+++ b/tools/testing/selftests/kvm/x86/xen_shinfo_test.c
@@ -350,17 +350,25 @@ static void guest_code(void)
 	p = (struct sched_poll) {
 		.ports = ports,
 		.nr_ports = 1,
-		.timeout = 0
+		/*
+		 * The poll must have a timeout: if the timer event is dropped
+		 * while we are already blocked in the poll, nothing else will
+		 * ever wake us, and the recovery protocol below could never
+		 * run. (As with TEST_POLL_TIMEOUT above, KVM treats the
+		 * timeout as relative.)
+		 */
+		.timeout = 10000000,
 	};
 
 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/16 23:00 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 24220
							output: 37
							thoughts: 421
						

Thoughts:
**Initial Assessment of KVM Patch Series**

Okay, so I've got a patch series here related to the KVM subsystem. My first step is to get a handle on the scope of the changes. The diff indicates modifications across several key areas: `Documentation/virt/kvm/api.rst`, the x86-specific KVM implementation (`arch/x86/kvm/`), core KVM files (`include/linux/kvm_host.h`, `include/linux/kvm_types.h`, `virt/kvm/pfncache.c`), and some test infrastructure (`tools/testing/selftests/kvm/`). Specifically, I see changes touching the KVM core, KVM x86 code, and even the KVM Xen emulation layer. This immediately tells me we're likely dealing with something that could impact a fairly broad range of virtualized environments, specifically amd64 which is our target.

Now, before diving too deep into the code, I need more context. I'll need to dig into the patch details, maybe check the git log entries if the commit messages aren't sufficient, or go straight to file inspection. Given KVM's importance, I need to verify that these changes don't introduce any regressions in standard virtualized setups (QEMU/KVM, `/dev/kvm` ioctls, nested virtualization scenarios, and importantly, syzkaller). I also need to verify KVM and KVM_XEN are standards, and are fuzzable.

My primary concern right now is to understand the intent and impact of these changes. I'll probably start with some strategic greps or perhaps even the git log to better understand the rationale behind the commits and the scope of the modifications. This will help me prioritize my review and identify any potential areas of concern.



4/2 2026/10/16 23:01 tool grepper
0m Args:
{
  "Expression": "KVM_XEN",
  "PathPrefixes": [
    "arch/x86/kvm/Kconfig"
  ]
}

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"
}

5/2 2026/10/16 23:01 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 25171
							output: 39
							thoughts: 29
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience, and presented as if they were my own thinking:

**Examining KVM x86 Configuration**

Right, let's dive straight in. I need to get a clear picture of the KVM x86 configuration options, particularly their dependencies and fine-grained details. Given my familiarity with the codebase, I'm thinking line 208 within `arch/x86/kvm/Kconfig` is a good starting point. That section usually holds the core settings related to KVM's x86 architecture support, and from experience, the associated dependencies are often explicitly defined there. I anticipate encountering the usual suspects – processor feature flags, relevant virtualization extensions, and perhaps some architecture-specific tuning options. This is where the crucial groundwork is laid, right? Understanding the configuration enables me to follow changes and assess their impact, at the very least, and hopefully, to identify any areas for optimization or potential conflicts based on my deeper knowledge of the hardware/software interactions. Let's see what we've got.



6/2 2026/10/16 23:01 tool read-file
0m Args:
{
  "File": "arch/x86/kvm/Kconfig",
  "FirstLine": 200,
  "LineCount": 30
}

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 225:\t\t  gates code that verifies a to-be-freed page table doesn't have any\n 226:\t\t  present SPTEs.\n 227:\t\n 228:\t\t  If in doubt, say \"N\".\n 229:\t\n"
}

7/2 2026/10/16 23:01 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 25939
							output: 37
							thoughts: 27
						

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

**Investigating KVM Configuration in the x86 Architecture**

Okay, so I need to understand the KVM configuration better, specifically within the x86 architecture. My first instinct, as always, is to dive into the core configuration files. Therefore, I need to check the Kconfig file that likely controls the relevant options. I'm going to head straight to `arch/x86/kvm/Kconfig` to see what's defined there. That's usually the best place to start when debugging or understanding how these features are brought into the build. I'm hoping it's well-structured, so I can quickly identify the KVM-related settings I'm interested in, like `KVM_X86` and any associated flags, dependencies, and default values. This should provide me with a solid foundation.



8/2 2026/10/16 23:01 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"
}

9/2 2026/10/16 23:01 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 26928
							output: 35
							thoughts: 25
						

Thoughts:
Here's a summary of my thought process, as requested:

**KVM PFNCACHE Checkpoint**

Okay, let's zero in on this KVM-related issue. My immediate first step is to confirm the presence and status of `HAVE_KVM_PFNCACHE`. I'm going to start by diving into the `virt/kvm/Kconfig` file. That's the logical place to look for the configuration option definition, dependencies, and any associated documentation. Understanding how that's defined will quickly inform the scope of this work and help me understand its implications if present or absent. That'll be my starting point for troubleshooting or modification if required.



10/2 2026/10/16 23:02 tool grepper
0m Args:
{
  "Expression": "HAVE_KVM_PFNCACHE",
  "PathPrefixes": [
    "virt/kvm/"
  ]
}

Results:
{
  "Output": "virt/kvm/Kconfig=4=config KVM_COMMON\n--\nvirt/kvm/Kconfig-10-\nvirt/kvm/Kconfig:11:config HAVE_KVM_PFNCACHE\nvirt/kvm/Kconfig-12-       bool\n--\nvirt/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--\nvirt/kvm/kvm_mm.h=59=kvm_pfn_t hva_to_pfn(struct kvm_follow_pfn *kfp);\nvirt/kvm/kvm_mm.h-60-\nvirt/kvm/kvm_mm.h:61:#ifdef CONFIG_HAVE_KVM_PFNCACHE\nvirt/kvm/kvm_mm.h-62-void gfn_to_pfn_cache_invalidate_start(struct kvm *kvm,\n--\nvirt/kvm/kvm_mm.h=66=static inline void gfn_to_pfn_cache_invalidate_start(struct kvm *kvm,\n--\nvirt/kvm/kvm_mm.h-70-}\nvirt/kvm/kvm_mm.h:71:#endif /* HAVE_KVM_PFNCACHE */\nvirt/kvm/kvm_mm.h-72-\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 27561
							output: 54
							thoughts: 85
						

Thoughts:
Okay, let's break this down.

**KVM on x86: Dependencies and Configuration**

Right, so I'm thinking about building KVM on an x86 system. I need to make sure I have all the necessary components. First, obviously KVM itself. Then, I'll need either KVM_INTEL or KVM_AMD, as these are the crucial elements for enabling the x86 specific aspects. This is important, as these selections trigger KVM_X86, which is fundamental to the x86 architecture support. Additionally, it looks like KVM_XEN is also an option, enabling Xen support, should that be needed.

My next step is to examine the `arch/x86/kvm/Kconfig` file. This is where I'll find all the detailed KVM configuration options specific to the x86 architecture. Time to dive in and confirm my understanding.



12/2 2026/10/16 23:02 tool grepper
0m Args:
{
  "Expression": "config KVM\\b|config KVM_INTEL\\b|config KVM_AMD\\b",
  "PathPrefixes": [
    "arch/x86/kvm/Kconfig"
  ]
}

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--\narch/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=134=config KVM_INTEL_TDX\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"
}

13/2 2026/10/16 23:02 llm patch-evaluator
2m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 28200
							output: 36
							thoughts: 1943
						

Thoughts:
**Detailed Analysis of KVM Patchset for Fuzzing Potential**

Okay, let's break down these patch changes methodically. My initial assessment screams "fuzzing target" due to the core KVM modifications and concurrency-related aspects.

First, I see a significant focus on `gfn_to_pfn_cache` (GPC) management, particularly in `virt/kvm/pfncache.c`.  The changes around `__kvm_gpc_refresh`, `kvm_gpc_refresh`, `__kvm_gpc_init`, and `__kvm_gpc_activate` immediately grab my attention. Specifically, the introduction of a `wait` parameter to some functions and the looping on `-EAGAIN` indicate that this is about handling asynchronous operations and potentially resolving race conditions during memory slot updates, which are known hot spots for KVM exploits. I notice the `lockdep annotation` with `srcu_lock_sync` and, even more importantly, the `!fatal_signal_pending(current)` checks which could be abused.

Next, I'm diving into `arch/x86/kvm/xen.c`. This is where it gets interesting, as it indicates a concerted effort to integrate KVM with Xen's PV (Paravirtualization) and HVM (Hardware Virtual Machine) modes.  Functions like `kvm_xen_shared_info_init`, `kvm_xen_inject_timer_irqs`, and the various calls to `kvm_gpc_refresh` and `kvm_gpc_activate` are prime areas. I'm noting the removal of `kvm_gpc_mark_dirty_in_slot` in `kvm_xen_inject_pending_events` and the explicit `wait` parameter passed to several of these functions: This could lead to a use-after-free or a deadlock in the corner case. The lock dropping around `kvm_xen_shared_info_init` and `kvm_gpc_activate` is also a potential race condition. The handling of `-EAGAIN` returns in `kvm_xen_hypercall` and `__kvm_xen_set_evtchn_fast` with lock handling changes are particularly intriguing. The GPC read lock dropping is also an interesting one, and requires careful verification.

Now, into `arch/x86/kvm/x86.c`. Here, the TLB flush handling in `record_steal_time` and the `vcpu_enter_guest` function are key.  The refactoring to use `kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu)` suggests a move towards a more asynchronous approach. This deferred flush coupled with the moved check `kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu)` opens up opportunities for inconsistencies if not carefully synchronized.

Lastly, `arch/x86/kvm/msrs.c` shows changes with `kvm_gpc_activate` and is related to the PV clock implementation. I suspect that the changes here are related to memory synchronization and Xen interaction as well.

Based on this deep dive, I'm confident that this patchset is a strong candidate for fuzzing. It addresses concurrency issues (races, deadlocks) within KVM's core memory management, Xen interaction, and x86 specific features. The code is readily reachable through standard KVM interfaces exposed by `/dev/kvm`.  Syzkaller can readily exercise most of this code, as it already supports ioctls like `KVM_CREATE_VM`, `KVM_CREATE_VCPU`, and memslot manipulation. The patch modifies executable code in core areas. The code refactoring and lock dropping are also prime fuzzing targets.

As far as the configuration goes: to enable and test this, I need `KVM`, `KVM_X86`, and `KVM_XEN` enabled in the kernel config.

Therefore, this is a definite "WorthFuzzing = true". Now I need to design test cases targeting those areas.



14/2 2026/10/16 23:04 tool grepper
0m Args:
{
  "Expression": "xen|pfncache",
  "PathPrefixes": [
    "arch/x86/kvm/Makefile"
  ]
}

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"
}

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

Args:
null

Results:
null

Tokens:
							input: 31183
							output: 36
							thoughts: 54
						

Thoughts:
Okay, here's my take on those thoughts, framed as my own reasoning:

**KVM and Xen Integration: A Quick Look**

Alright, so `CONFIG_KVM_XEN` is clearly bringing `xen.o` into the mix, which suggests some level of integration or co-existence with Xen. Let's dig in a bit further to see how `kvm` is *generally* built within the x86 architecture, specifically in `arch/x86/kvm/Makefile`. I want to understand the base build process before I can really understand how Xen is brought in and what the dependencies might look like. This will hopefully show the linkage between the kvm build and the inclusion of xen, and any potential configuration impacts.



16/2 2026/10/16 23:05 tool read-file
0m Args:
{
  "File": "arch/x86/kvm/Makefile",
  "FirstLine": 1,
  "LineCount": 25
}

Results:
{
  "Contents": "   1:\t# SPDX-License-Identifier: GPL-2.0\n   2:\t\n   3:\tccflags-y += -I $(srctree)/arch/x86/kvm\n   4:\tccflags-$(CONFIG_KVM_WERROR) += -Werror\n   5:\t\n   6:\tinclude $(srctree)/virt/kvm/Makefile.kvm\n   7:\t\n   8:\tkvm-y\t\t\t+= x86.o emulate.o irq.o lapic.o cpuid.o msrs.o pmu.o regs.o \\\n   9:\t\t\t\t   mtrr.o debugfs.o mmu/mmu.o mmu/page_track.o mmu/spte.o\n  10:\t\n  11:\tkvm-$(CONFIG_X86_64) += mmu/tdp_iter.o mmu/tdp_mmu.o\n  12:\tkvm-$(CONFIG_KVM_IOAPIC) += i8259.o i8254.o ioapic.o\n  13:\tkvm-$(CONFIG_KVM_HYPERV) += hyperv.o\n  14:\tkvm-$(CONFIG_KVM_XEN)\t+= xen.o\n  15:\tkvm-$(CONFIG_KVM_SMM)\t+= smm.o\n  16:\t\n  17:\tkvm-intel-y\t\t+= vmx/vmx.o vmx/vmenter.o vmx/pmu_intel.o vmx/vmcs12.o \\\n  18:\t\t\t\t   vmx/nested.o vmx/posted_intr.o vmx/main.o\n  19:\t\n  20:\tkvm-intel-$(CONFIG_X86_SGX_KVM)\t+= vmx/sgx.o\n  21:\tkvm-intel-$(CONFIG_KVM_HYPERV)\t+= vmx/hyperv.o vmx/hyperv_evmcs.o\n  22:\tkvm-intel-$(CONFIG_KVM_INTEL_TDX)\t+= vmx/tdx.o\n  23:\t\n  24:\tkvm-amd-y\t\t+= svm/svm.o svm/vmenter.o svm/pmu.o svm/nested.o svm/avic.o\n  25:\t\n"
}

17/2 2026/10/16 23:05 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 32018
							output: 37
							thoughts: 294
						

Thoughts:
**Analyzing the KVM PFN Cache Build Process**

Okay, let's break down how this `pfncache.c` file is getting built. My initial thought is to trace the build path. I see it's linked in `virt/kvm/Makefile.kvm` like this: `kvm-$(CONFIG_HAVE_KVM_PFNCACHE) += $(KVM)/pfncache.o`. Right, so `HAVE_KVM_PFNCACHE` is the key. Now, where is that defined? Ah, it's selected by `KVM_X86`. That makes sense; it's specific to the x86 architecture.

Let's dig deeper into the dependencies. `KVM_X86` is defined as a tristate option and is only enabled if either `KVM_INTEL` *or* `KVM_AMD` isn't set to 'n'. Now, `KVM_XEN` has a dependency on `KVM_X86`. And both `KVM_INTEL` and `KVM_AMD` depend on the base `KVM` option. That's good; it's all making sense.

So, to get KVM up and running on x86, it looks like we need `KVM`, either `KVM_INTEL` or `KVM_AMD`, and `KVM_XEN` enabled. Just to be thorough, I should look for other config options that might influence this. Let's make sure I didn't miss something. I will check for the usage of `KVM_X86` directly. Ah yes, I see it's defined the same way: a tristate dependent on `KVM_INTEL` or `KVM_AMD` not being 'n'. 

Just to be absolutely sure, I'll go to `arch/x86/kvm/Kconfig` to check the specific dependencies of `KVM_INTEL` and `KVM_AMD`. Better to cover all bases.



18/2 2026/10/16 23:05 tool grepper
0m Args:
{
  "Expression": "depends on.*KVM",
  "PathPrefixes": [
    "arch/x86/kvm/Kconfig"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/Kconfig=69=config KVM_WERROR\n--\narch/x86/kvm/Kconfig-76-\t# the kernel-wide WERROR=y.\narch/x86/kvm/Kconfig:77:\tdepends on KVM_X86 \u0026\u0026 ((EXPERT \u0026\u0026 !KASAN) || WERROR)\narch/x86/kvm/Kconfig-78-\thelp\n--\narch/x86/kvm/Kconfig=83=config KVM_SW_PROTECTED_VM\n--\narch/x86/kvm/Kconfig-85-\tdepends on EXPERT\narch/x86/kvm/Kconfig:86:\tdepends on KVM_X86 \u0026\u0026 X86_64\narch/x86/kvm/Kconfig-87-\tselect KVM_GENERIC_MEMORY_ATTRIBUTES\n--\narch/x86/kvm/Kconfig=96=config KVM_INTEL\narch/x86/kvm/Kconfig-97-\ttristate \"KVM for Intel (and compatible) processors support\"\narch/x86/kvm/Kconfig:98:\tdepends on KVM \u0026\u0026 IA32_FEAT_CTL\narch/x86/kvm/Kconfig-99-\tselect X86_FRED if X86_64\n--\narch/x86/kvm/Kconfig=107=config KVM_INTEL_PROVE_VE\narch/x86/kvm/Kconfig-108-        bool \"Check that guests do not receive #VE exceptions\"\narch/x86/kvm/Kconfig:109:        depends on KVM_INTEL \u0026\u0026 EXPERT\narch/x86/kvm/Kconfig-110-        help\n--\narch/x86/kvm/Kconfig=122=config X86_SGX_KVM\narch/x86/kvm/Kconfig-123-\tbool \"Software Guard eXtensions (SGX) Virtualization\"\narch/x86/kvm/Kconfig:124:\tdepends on X86_SGX \u0026\u0026 KVM_INTEL\narch/x86/kvm/Kconfig-125-\thelp\n--\narch/x86/kvm/Kconfig=146=config KVM_AMD\narch/x86/kvm/Kconfig-147-\ttristate \"KVM for AMD processors support\"\narch/x86/kvm/Kconfig:148:\tdepends on KVM \u0026\u0026 (CPU_SUP_AMD || CPU_SUP_HYGON)\narch/x86/kvm/Kconfig-149-\thelp\n--\narch/x86/kvm/Kconfig=156=config KVM_AMD_SEV\n--\narch/x86/kvm/Kconfig-158-\tdefault y\narch/x86/kvm/Kconfig:159:\tdepends on KVM_AMD \u0026\u0026 X86_64\narch/x86/kvm/Kconfig:160:\tdepends on CRYPTO_DEV_SP_PSP \u0026\u0026 !(KVM_AMD=y \u0026\u0026 CRYPTO_DEV_CCP_DD=m)\narch/x86/kvm/Kconfig-161-\tselect ARCH_HAS_CC_PLATFORM\n--\narch/x86/kvm/Kconfig=173=config KVM_IOAPIC\n--\narch/x86/kvm/Kconfig-175-\tdefault y\narch/x86/kvm/Kconfig:176:\tdepends on KVM_X86\narch/x86/kvm/Kconfig-177-\thelp\n--\narch/x86/kvm/Kconfig=183=config KVM_SMM\n--\narch/x86/kvm/Kconfig-185-\tdefault y\narch/x86/kvm/Kconfig:186:\tdepends on KVM_X86\narch/x86/kvm/Kconfig-187-\thelp\n--\narch/x86/kvm/Kconfig=194=config KVM_HYPERV\narch/x86/kvm/Kconfig-195-\tbool \"Support for Microsoft Hyper-V emulation\"\narch/x86/kvm/Kconfig:196:\tdepends on KVM_X86\narch/x86/kvm/Kconfig-197-\tdefault y\n--\narch/x86/kvm/Kconfig=208=config KVM_XEN\narch/x86/kvm/Kconfig-209-\tbool \"Support for Xen hypercall interface\"\narch/x86/kvm/Kconfig:210:\tdepends on KVM_X86\narch/x86/kvm/Kconfig-211-\thelp\n--\narch/x86/kvm/Kconfig=217=config KVM_PROVE_MMU\n--\narch/x86/kvm/Kconfig-219-\tdepends on DEBUG_KERNEL\narch/x86/kvm/Kconfig:220:\tdepends on KVM_X86\narch/x86/kvm/Kconfig-221-\tdepends on EXPERT\n--\narch/x86/kvm/Kconfig=233=config KVM_MAX_NR_VCPUS\narch/x86/kvm/Kconfig-234-\tint \"Maximum number of vCPUs per KVM guest\"\narch/x86/kvm/Kconfig:235:\tdepends on KVM_X86\narch/x86/kvm/Kconfig-236-\trange 1024 4096\n"
}

19/2 2026/10/16 23:05 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 34224
							output: 35
							thoughts: 1486
						

Thoughts:
**Focusing on Key KVM Subsystem Logic**

Alright, let's map out these `FocusSymbols` for KVM on amd64, considering `KVM`, `KVM_INTEL`, `KVM_AMD`, and `KVM_XEN` configurations. My goal is to pinpoint the functions that are *specifically* implementing or modifying the logic within the diff, while avoiding overly ubiquitous hot-path functions.

I need to focus on direct API entrypoints or functions that directly implement or alter specific features. Looking at the modified functions, I see the following spread across the files:

*   **`virt/kvm/pfncache.c`**: There's a mix of static and non-static functions related to the PFN cache. I need to single out the non-static and exported ones that are feature-specific. I'm focusing on `kvm_gpc_refresh` and `kvm_gpc_activate`.

*   **`arch/x86/kvm/xen.c`**: This is where things get interesting, especially with Xen integration. I need to identify the key entrypoints and feature-specific functions here.

*   **`arch/x86/kvm/x86.c`**: We have `record_steal_time` called from `vcpu_enter_guest` which is a problem as `vcpu_enter_guest` is a core KVM function. It's a very ubiquitous hot-path in KVM, called thousands of times per guest entry, so I need to filter it out.

*   **`arch/x86/kvm/msrs.c`**: This has `kvm_write_system_time`, but it is static and less relevant to the direct focus.

Now, let's drill down into `arch/x86/kvm/xen.c`. I'm specifically looking for functions that are *non-static* and act as direct API entrypoints or key logic implementations. I've noted:

*   `kvm_xen_hvm_set_attr`, `kvm_xen_vcpu_set_attr`, `kvm_xen_vcpu_get_attr`: These directly handle ioctls related to Xen HVM and VCPU attributes. They're definitely in scope.
*   `kvm_xen_hvm_evtchn_send`: This one handles the `KVM_XEN_HVM_EVTCHN_SEND` ioctl, so it's a good candidate.
*   `kvm_xen_set_evtchn_fast`: This is called for injecting event channels, so it seems important.
*   `kvm_xen_hypercall`: This handles Xen hypercalls, which is crucial.
*   `kvm_xen_inject_timer_irqs` and `kvm_xen_inject_pending_events`: These are called on guest entry to handle timer interrupts and pending events, respectively. These seem relevant.
*   `kvm_xen_write_hypercall_page`: This is called when the guest writes Xen hypercall MSR; this also seem important.

In `virt/kvm/pfncache.c` I decided to focus on `kvm_gpc_refresh` and `kvm_gpc_activate`.

I'll check the visibility of these functions by looking at the `.h` files or the code itself for any export declarations, ensuring I only include what's necessary, and avoid the common functions to make my filter as accurate as possible.



20/2 2026/10/16 23:05 tool grepper
0m Args:
{
  "Expression": "kvm_xen_",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "\nFull output is too long, showing 200 out of 750 lines.\nUse more precise expression or PathPrefixes if possible.\n\nNumber of matching lines per file (8 files in total):\narch/x86/kvm/hyperv.c:1\narch/x86/kvm/irq.c:8\narch/x86/kvm/lapic.c:1\narch/x86/kvm/msrs.c:2\narch/x86/kvm/trace.h:1\narch/x86/kvm/x86.c:27\narch/x86/kvm/xen.c:108\narch/x86/kvm/xen.h:58\n\narch/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/irq.c=27=int kvm_cpu_has_pending_timer(struct kvm_vcpu *vcpu)\n--\narch/x86/kvm/irq.c-32-\t\tr = apic_has_pending_timer(vcpu);\narch/x86/kvm/irq.c:33:\tif (kvm_xen_timer_enabled(vcpu))\narch/x86/kvm/irq.c:34:\t\tr += kvm_xen_has_pending_timer(vcpu);\narch/x86/kvm/irq.c-35-\n--\narch/x86/kvm/irq.c=59=int kvm_cpu_has_extint(struct kvm_vcpu *v)\n--\narch/x86/kvm/irq.c-74-\narch/x86/kvm/irq.c:75:\tif (kvm_xen_has_interrupt(v))\narch/x86/kvm/irq.c-76-\t\treturn 1;\n--\narch/x86/kvm/irq.c=128=int kvm_cpu_get_extint(struct kvm_vcpu *v)\n--\narch/x86/kvm/irq.c-138-#ifdef CONFIG_KVM_XEN\narch/x86/kvm/irq.c:139:\tif (kvm_xen_has_interrupt(v))\narch/x86/kvm/irq.c-140-\t\treturn v-\u003ekvm-\u003earch.xen.upcall_vector;\n--\narch/x86/kvm/irq.c=169=void kvm_inject_pending_timer_irqs(struct kvm_vcpu *vcpu)\n--\narch/x86/kvm/irq.c-172-\t\tkvm_inject_apic_timer_irqs(vcpu);\narch/x86/kvm/irq.c:173:\tif (kvm_xen_timer_enabled(vcpu))\narch/x86/kvm/irq.c:174:\t\tkvm_xen_inject_timer_irqs(vcpu);\narch/x86/kvm/irq.c-175-}\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-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/irq.c=296=int kvm_set_routing_entry(struct kvm *kvm,\n--\narch/x86/kvm/irq.c-347-\tcase KVM_IRQ_ROUTING_XEN_EVTCHN:\narch/x86/kvm/irq.c:348:\t\treturn kvm_xen_setup_evtchn(kvm, e, ue);\narch/x86/kvm/irq.c-349-#endif\n--\narch/x86/kvm/lapic.c=527=static inline void apic_set_spiv(struct kvm_lapic *apic, u32 val)\n--\narch/x86/kvm/lapic.c-545-\t\tkvm_make_request(KVM_REQ_APF_READY, apic-\u003evcpu);\narch/x86/kvm/lapic.c:546:\t\tkvm_xen_sw_enable_lapic(apic-\u003evcpu);\narch/x86/kvm/lapic.c-547-\t}\n--\narch/x86/kvm/msrs.c=1442=int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)\n--\narch/x86/kvm/msrs.c-1451-\t */\narch/x86/kvm/msrs.c:1452:\tif (kvm_xen_is_hypercall_page_msr(vcpu-\u003ekvm, msr) \u0026\u0026\narch/x86/kvm/msrs.c-1453-\t    !msr_info-\u003ehost_initiated)\narch/x86/kvm/msrs.c:1454:\t\treturn kvm_xen_write_hypercall_page(vcpu, data);\narch/x86/kvm/msrs.c-1455-\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=2048=static void record_steal_time(struct kvm_vcpu *vcpu)\n--\narch/x86/kvm/x86.c-2056-\narch/x86/kvm/x86.c:2057:\tif (kvm_xen_msr_enabled(vcpu-\u003ekvm)) {\narch/x86/kvm/x86.c:2058:\t\tkvm_xen_runstate_set_running(vcpu);\narch/x86/kvm/x86.c-2059-\t\treturn;\n--\narch/x86/kvm/x86.c=2676=void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)\n--\narch/x86/kvm/x86.c-2693-\t\tidx = srcu_read_lock(\u0026vcpu-\u003ekvm-\u003esrcu);\narch/x86/kvm/x86.c:2694:\t\tif (kvm_xen_msr_enabled(vcpu-\u003ekvm))\narch/x86/kvm/x86.c:2695:\t\t\tkvm_xen_runstate_set_preempted(vcpu);\narch/x86/kvm/x86.c-2696-\t\telse\n--\narch/x86/kvm/x86.c=3430=long kvm_arch_vcpu_ioctl(struct file *filp,\n--\narch/x86/kvm/x86.c-3829-\tcase KVM_XEN_VCPU_GET_ATTR: {\narch/x86/kvm/x86.c:3830:\t\tstruct kvm_xen_vcpu_attr xva;\narch/x86/kvm/x86.c-3831-\n--\narch/x86/kvm/x86.c-3834-\t\t\tgoto out;\narch/x86/kvm/x86.c:3835:\t\tr = kvm_xen_vcpu_get_attr(vcpu, \u0026xva);\narch/x86/kvm/x86.c-3836-\t\tif (!r \u0026\u0026 copy_to_user(argp, \u0026xva, sizeof(xva)))\n--\narch/x86/kvm/x86.c-3840-\tcase KVM_XEN_VCPU_SET_ATTR: {\narch/x86/kvm/x86.c:3841:\t\tstruct kvm_xen_vcpu_attr xva;\narch/x86/kvm/x86.c-3842-\n--\narch/x86/kvm/x86.c-3845-\t\t\tgoto out;\narch/x86/kvm/x86.c:3846:\t\tr = kvm_xen_vcpu_set_attr(vcpu, \u0026xva);\narch/x86/kvm/x86.c-3847-\t\tbreak;\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-4619-\tcase KVM_XEN_HVM_CONFIG: {\narch/x86/kvm/x86.c:4620:\t\tstruct kvm_xen_hvm_config xhc;\narch/x86/kvm/x86.c-4621-\t\tr = -EFAULT;\n--\narch/x86/kvm/x86.c-4623-\t\t\tgoto out;\narch/x86/kvm/x86.c:4624:\t\tr = kvm_xen_hvm_config(kvm, \u0026xhc);\narch/x86/kvm/x86.c-4625-\t\tbreak;\n--\narch/x86/kvm/x86.c-4627-\tcase KVM_XEN_HVM_GET_ATTR: {\narch/x86/kvm/x86.c:4628:\t\tstruct kvm_xen_hvm_attr xha;\narch/x86/kvm/x86.c-4629-\n--\narch/x86/kvm/x86.c-4632-\t\t\tgoto out;\narch/x86/kvm/x86.c:4633:\t\tr = kvm_xen_hvm_get_attr(kvm, \u0026xha);\narch/x86/kvm/x86.c-4634-\t\tif (!r \u0026\u0026 copy_to_user(argp, \u0026xha, sizeof(xha)))\n--\narch/x86/kvm/x86.c-4638-\tcase KVM_XEN_HVM_SET_ATTR: {\narch/x86/kvm/x86.c:4639:\t\tstruct kvm_xen_hvm_attr xha;\narch/x86/kvm/x86.c-4640-\n--\narch/x86/kvm/x86.c-4643-\t\t\tgoto out;\narch/x86/kvm/x86.c:4644:\t\tr = kvm_xen_hvm_set_attr(kvm, \u0026xha);\narch/x86/kvm/x86.c-4645-\t\tbreak;\n--\narch/x86/kvm/x86.c-4652-\t\t\tgoto out;\narch/x86/kvm/x86.c:4653:\t\tr = kvm_xen_hvm_evtchn_send(kvm, \u0026uxe);\narch/x86/kvm/x86.c-4654-\t\tbreak;\n--\narch/x86/kvm/x86.c=7172=void kvm_x86_vendor_exit(void)\n--\narch/x86/kvm/x86.c-7196-#ifdef CONFIG_KVM_XEN\narch/x86/kvm/x86.c:7197:\tstatic_key_deferred_flush(\u0026kvm_xen_enabled);\narch/x86/kvm/x86.c:7198:\tWARN_ON(static_branch_unlikely(\u0026kvm_xen_enabled.key));\narch/x86/kvm/x86.c-7199-#endif\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/x86.c=8065=static int vcpu_enter_guest(struct kvm_vcpu *vcpu)\n--\narch/x86/kvm/x86.c-8244-\tif (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win ||\narch/x86/kvm/x86.c:8245:\t    kvm_xen_has_interrupt(vcpu)) {\narch/x86/kvm/x86.c-8246-\t\t++vcpu-\u003estat.req_event;\n--\narch/x86/kvm/x86.c=8530=bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)\n--\narch/x86/kvm/x86.c-8568-\narch/x86/kvm/x86.c:8569:\tif (kvm_xen_has_pending_events(vcpu))\narch/x86/kvm/x86.c-8570-\t\treturn true;\n--\narch/x86/kvm/x86.c=8651=static int vcpu_run(struct kvm_vcpu *vcpu)\n--\narch/x86/kvm/x86.c-8674-\t\tkvm_clear_request(KVM_REQ_UNBLOCK, vcpu);\narch/x86/kvm/x86.c:8675:\t\tif (kvm_xen_has_pending_events(vcpu))\narch/x86/kvm/x86.c:8676:\t\t\tkvm_xen_inject_pending_events(vcpu);\narch/x86/kvm/x86.c-8677-\n--\narch/x86/kvm/x86.c=9360=int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)\n--\narch/x86/kvm/x86.c-9430-\narch/x86/kvm/x86.c:9431:\tkvm_xen_init_vcpu(vcpu);\narch/x86/kvm/x86.c-9432-\tvcpu_load(vcpu);\n--\narch/x86/kvm/x86.c=9471=void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)\n--\narch/x86/kvm/x86.c-9488-\narch/x86/kvm/x86.c:9489:\tkvm_xen_destroy_vcpu(vcpu);\narch/x86/kvm/x86.c-9490-\tkvm_hv_vcpu_uninit(vcpu);\n--\narch/x86/kvm/x86.c=9863=int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)\n--\narch/x86/kvm/x86.c-9915-\tkvm_hv_init_vm(kvm);\narch/x86/kvm/x86.c:9916:\tkvm_xen_init_vm(kvm);\narch/x86/kvm/x86.c-9917-\n--\narch/x86/kvm/x86.c=10034=void kvm_arch_destroy_vm(struct kvm *kvm)\n--\narch/x86/kvm/x86.c-10061-\tkvm_page_track_cleanup(kvm);\narch/x86/kvm/x86.c:10062:\tkvm_xen_destroy_vm(kvm);\narch/x86/kvm/x86.c-10063-\tkvm_hv_destroy_vm(kvm);\n--\narch/x86/kvm/xen.c-32-\narch/x86/kvm/xen.c:33:static int kvm_xen_set_evtchn(struct kvm_xen_evtchn *xe, struct kvm *kvm,\narch/x86/kvm/xen.c-34-\t\t\t      bool wait);\narch/x86/kvm/xen.c:35:static int kvm_xen_setattr_evtchn(struct kvm *kvm, struct kvm_xen_hvm_attr *data);\narch/x86/kvm/xen.c:36:static int kvm_xen_hcall_evtchn_send(struct kvm_vcpu *vcpu, u64 param, u64 *r);\narch/x86/kvm/xen.c-37-\narch/x86/kvm/xen.c:38:DEFINE_STATIC_KEY_DEFERRED_FALSE(kvm_xen_enabled, HZ);\narch/x86/kvm/xen.c-39-\n--\narch/x86/kvm/xen.c=48=static inline int kvm_max_evtchn_port(struct kvm *kvm)\narch/x86/kvm/xen.c-49-{\narch/x86/kvm/xen.c:50:\treturn max_evtchn_port(kvm_xen_has_64bit_shinfo(kvm));\narch/x86/kvm/xen.c-51-}\narch/x86/kvm/xen.c-52-\narch/x86/kvm/xen.c:53:static int kvm_xen_shared_info_init(struct kvm *kvm, bool wait)\narch/x86/kvm/xen.c-54-{\n--\narch/x86/kvm/xen.c-96-\n\n"
}

21/2 2026/10/16 23:05 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 41546
							output: 328
							thoughts: 1418
						

Thoughts:
**Analysis of KVM Xen Emulation Patch Series**

Okay, let's break this down. First, I'm noting the functions modified in `arch/x86/kvm/xen.c` and `virt/kvm/pfncache.c`. These are my initial focus: `kvm_xen_hvm_set_attr`, `kvm_xen_vcpu_set_attr`, `kvm_xen_vcpu_get_attr`, `kvm_xen_hvm_evtchn_send`, `kvm_xen_write_hypercall_page`, `kvm_xen_hypercall`, `kvm_xen_set_evtchn_fast`, `kvm_xen_inject_timer_irqs`, `kvm_gpc_refresh`, `kvm_gpc_activate`.

Are any of these "FocusSymbols" in the ubiquitous sense? No, these are clearly specialized. They're all targeted to Xen emulation on KVM or the `gfn_to_pfn_cache` (GPC) operations within KVM. Specifically we see functions directly related to Xen hypercalls and event channel handling, and memory cache refresh/activation. I'm noting the specifics to ensure clarity in my analysis.

I'm also checking `record_steal_time`, which is static in `x86.c`. Given that static functions can be inlined, they are less valuable as FocusSymbols. We avoid them per guidance, as they lack distinct symbol addresses in the vmlinux. This clarifies why I'm listing the non-static symbols.

Now, let's review the required configurations. It's `KVM`, `KVM_INTEL`, `KVM_AMD`, and `KVM_XEN`. `KVM_XEN` depends on `KVM_X86`, which in turn depends on either `KVM_INTEL` or `KVM_AMD`. This implies users enable `KVM`, and *one* of `KVM_INTEL` or `KVM_AMD`, and `KVM_XEN` to fully activate the relevant code. `HAVE_KVM_PFNCACHE` is selected by KVM, so it's not a user-facing concern.

Alright, with that foundation, let's prepare the reasoning for the fuzzing decision.

*   **Patch Summary**: This series addresses concurrency and deadlock issues between memslot updates and GPC operations. It zeroes in on KVM's Xen emulation. Specifically, it tackles races that appear in `EVTCHNOP_send` and event channel delivery, alongside memslot deletion, recreation, locking order, and timer delivery retries, as well as steal time TLB flush deferral.

*   **Reachability**: KVM is fully reachable via standard `/dev/kvm` ioctls and vCPU execution in standard QEMU/KVM virtualized environments. This means it's straightforward to trigger these codepaths. No special hardware is required.

*   **Fuzzing Worthiness**: The core of the changes lie in KVM memory caching (`pfncache.c`) and Xen emulation state machines with locking (`arch/x86/kvm/xen.c`, and `arch/x86/kvm/x86.c`). Given the focus on concurrency, races, and locking in hypercall and interrupt injection paths, these are exceptionally high-value targets for syzkaller fuzzing. The likelihood of uncovering subtle, exploitable bugs in these areas is high.

*   **Verdict:** This is a clear case for `WorthFuzzing = true`. The changes are directly relevant to areas of high concern.



22/2 2026/10/16 23:06 tool set-results
0m Args:
{
  "EnableConfigs": [
    "KVM",
    "KVM_INTEL",
    "KVM_AMD",
    "KVM_XEN"
  ],
  "FocusSymbols": [
    "kvm_gpc_refresh",
    "kvm_gpc_activate",
    "kvm_xen_hvm_set_attr",
    "kvm_xen_vcpu_set_attr",
    "kvm_xen_vcpu_get_attr",
    "kvm_xen_hypercall",
    "kvm_xen_hvm_evtchn_send",
    "kvm_xen_set_evtchn_fast",
    "kvm_xen_inject_timer_irqs",
    "kvm_xen_write_hypercall_page"
  ],
  "Reasoning": "The patch series refactors locking, synchronization, and race handling between memslot updates and gfn_to_pfn_cache (GPC) operations in KVM, specifically focusing on KVM Xen emulation (such as event channel delivery, timer IRQ injection, and hypercall handling racing against memslot deletion). These changes touch core reachable virtualization logic in virt/kvm/pfncache.c and arch/x86/kvm/xen.c, which are exercisable via /dev/kvm ioctls and guest hypercalls in standard virtualized environments. Because of the subtle concurrency semantics, lockdep assertions, and state management changes, this patch series warrants fuzzing.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "KVM",
    "KVM_INTEL",
    "KVM_AMD",
    "KVM_XEN"
  ],
  "FocusSymbols": [
    "kvm_gpc_refresh",
    "kvm_gpc_activate",
    "kvm_xen_hvm_set_attr",
    "kvm_xen_vcpu_set_attr",
    "kvm_xen_vcpu_get_attr",
    "kvm_xen_hypercall",
    "kvm_xen_hvm_evtchn_send",
    "kvm_xen_set_evtchn_fast",
    "kvm_xen_inject_timer_irqs",
    "kvm_xen_write_hypercall_page"
  ],
  "Reasoning": "The patch series refactors locking, synchronization, and race handling between memslot updates and gfn_to_pfn_cache (GPC) operations in KVM, specifically focusing on KVM Xen emulation (such as event channel delivery, timer IRQ injection, and hypercall handling racing against memslot deletion). These changes touch core reachable virtualization logic in virt/kvm/pfncache.c and arch/x86/kvm/xen.c, which are exercisable via /dev/kvm ioctls and guest hypercalls in standard virtualized environments. Because of the subtle concurrency semantics, lockdep assertions, and state management changes, this patch series warrants fuzzing.",
  "WorthFuzzing": true
}

23/1 2026/10/16 23:06 action If
2m Args:
{
  "WorthFuzzing": true
}

Results:
null

24/2 2026/10/16 23:06 agent kmsan-evaluator
2m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch series addresses deadlock and race conditions between KVM memslot updates and Xen emulation (specifically gfn_to_pfn_cache) when executed within SRCU read sections. The main modifications include:\n1. Introducing an -EAGAIN return when a memslot is transiently invalid (under churn) and adding a retry loop with a `wait` parameter to `kvm_gpc_activate()` and `kvm_gpc_refresh()`.\n2. Restructuring lock nesting around `xen_lock` and GPC read locks to ensure that memslot waits do not hold locks that could deadlock against SRCU readers.\n3. Deferring guest TLB flush requests (`KVM_REQ_TLB_FLUSH_GUEST`) during `record_steal_time()` and handling them on guest entry.\n4. Adding a `never_dirty` flag to `struct gfn_to_pfn_cache` to skip dirty page logging for Xen shared_info and vcpu_info.\n\nNone of these changes introduce or modify uninitialized memory access risks:\n- All new struct fields (`gpc-\u003enever_dirty`) and local variables (`inject_upcall`, `kick_vcpu`, `wait`, `rc`, etc.) are explicitly initialized before use.\n- No kernel-to-user memory transfers are modified in a way that risks uninitialized data or padding leaks (`kvm_xen_vcpu_get_attr` operates on an `xva` buffer populated by `copy_from_user`).\n- The hazards associated with this patch involve lock ordering, deadlocks, and race conditions during concurrent memslot updates and Xen event delivery. These are monitored by LOCKDEP and standard KASAN configurations. KMSAN does not provide additional detection capability here.",
  "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 d8614fa8ccb8870dac5d746557f59a5d34989939
Author: syz-cluster <triage@syzkaller.com>
Date:   Fri Oct 16 23:00:39 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..ed633a39a97a2 100644
--- a/arch/x86/include/asm/kvm_host.h
+++ b/arch/x86/include/asm/kvm_host.h
@@ -1108,6 +1108,12 @@ struct kvm_hv {
 #ifdef CONFIG_KVM_XEN
 /* Xen emulation context */
 struct kvm_xen {
+	/*
+	 * Taken from within kvm->srcu read sections (e.g. by a vCPU
+	 * writing the hypercall page MSR), so never held while waiting
+	 * out a memslot update: the update waits for those read
+	 * sections to quiesce.
+	 */
 	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..82adc5741f8db 100644
--- a/arch/x86/kvm/xen.c
+++ b/arch/x86/kvm/xen.c
@@ -30,13 +30,27 @@
 #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 inline int max_evtchn_port(bool has_64bit_shinfo)
+{
+	if (has_64bit_shinfo)
+		return EVTCHN_2L_NR_CHANNELS;
+	else
+		return COMPAT_EVTCHN_2L_NR_CHANNELS;
+}
+
+static inline int kvm_max_evtchn_port(struct kvm *kvm)
+{
+	return max_evtchn_port(kvm_xen_has_64bit_shinfo(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 +58,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 +119,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 +129,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);
@@ -155,21 +198,29 @@ static int xen_get_guest_pvclock(struct kvm_vcpu *vcpu,
 				 unsigned int offset)
 {
 	unsigned long flags;
-	int r;
+	int idx, r;
 
-	read_lock_irqsave(&gpc->lock, flags);
-	while (!kvm_gpc_check(gpc, offset + sizeof(*hv_clock))) {
+	/*
+	 * As in kvm_xen_shared_info_init(): kvm_gpc_check() consults the
+	 * memslots, so take kvm->srcu around each check and the copy, but
+	 * not across the refresh.
+	 */
+	for (;;) {
+		idx = srcu_read_lock(&vcpu->kvm->srcu);
+		read_lock_irqsave(&gpc->lock, flags);
+		if (kvm_gpc_check(gpc, offset + sizeof(*hv_clock)))
+			break;
 		read_unlock_irqrestore(&gpc->lock, flags);
+		srcu_read_unlock(&vcpu->kvm->srcu, idx);
 
-		r = kvm_gpc_refresh(gpc, offset + sizeof(*hv_clock));
+		r = kvm_gpc_refresh(gpc, offset + sizeof(*hv_clock), false);
 		if (r)
 			return r;
-
-		read_lock_irqsave(&gpc->lock, flags);
 	}
 
 	memcpy(hv_clock, gpc->khva + offset, sizeof(*hv_clock));
 	read_unlock_irqrestore(&gpc->lock, flags);
+	srcu_read_unlock(&vcpu->kvm->srcu, idx);
 
 	/*
 	 * Sanity check TSC shift+multiplier to verify the guest's view of time
@@ -435,7 +486,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 +539,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 +720,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 +756,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 +807,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.
@@ -784,27 +834,34 @@ int kvm_xen_hvm_set_attr(struct kvm *kvm, struct kvm_xen_hvm_attr *data)
 		} else {
 			mutex_lock(&kvm->arch.xen.xen_lock);
 			kvm->arch.xen.long_mode = !!data->u.long_mode;
+			mutex_unlock(&kvm->arch.xen.xen_lock);
 
 			/*
 			 * Re-initialize shared_info to put the wallclock in the
 			 * correct place. Whilst it's not necessary to do this
 			 * unless the mode is actually changed, it does no harm
-			 * to make the call anyway.
+			 * to make the call anyway. Done without xen_lock held:
+			 * the init may wait out a memslot update, and a vCPU
+			 * may block on xen_lock from within the kvm->srcu read
+			 * section which that update must wait out.
 			 */
 			r = kvm->arch.xen.shinfo_cache.active ?
-				kvm_xen_shared_info_init(kvm) : 0;
-			mutex_unlock(&kvm->arch.xen.xen_lock);
+				kvm_xen_shared_info_init(kvm, true) : 0;
 		}
 		break;
 
 	case KVM_XEN_ATTR_TYPE_SHARED_INFO:
 	case KVM_XEN_ATTR_TYPE_SHARED_INFO_HVA: {
-		int idx;
-
+		/*
+		 * Deactivation stays under xen_lock, but an activation may
+		 * wait out a memslot update and so must not hold it: a vCPU
+		 * may block on xen_lock from within the kvm->srcu read
+		 * section which that update must wait out. Concurrent
+		 * SET_ATTR calls racing in the window are userspace's own
+		 * race; the cache layer serializes them, last one wins.
+		 */
 		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;
 
@@ -812,8 +869,10 @@ int kvm_xen_hvm_set_attr(struct kvm *kvm, struct kvm_xen_hvm_attr *data)
 				kvm_gpc_deactivate(&kvm->arch.xen.shinfo_cache);
 				r = 0;
 			} else {
+				mutex_unlock(&kvm->arch.xen.xen_lock);
 				r = kvm_gpc_activate(&kvm->arch.xen.shinfo_cache,
-						     gfn_to_gpa(gfn), PAGE_SIZE);
+						     gfn_to_gpa(gfn), PAGE_SIZE, true);
+				mutex_lock(&kvm->arch.xen.xen_lock);
 			}
 		} else {
 			void __user * hva = u64_to_user_ptr(data->u.shared_info.hva);
@@ -829,12 +888,11 @@ int kvm_xen_hvm_set_attr(struct kvm *kvm, struct kvm_xen_hvm_attr *data)
 			}
 		}
 
-		srcu_read_unlock(&kvm->srcu, idx);
+		mutex_unlock(&kvm->arch.xen.xen_lock);
 
 		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;
 	}
 	case KVM_XEN_ATTR_TYPE_UPCALL_VECTOR:
@@ -937,7 +995,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:
@@ -959,8 +1016,16 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
 			if (!IS_ALIGNED(data->u.gpa, sizeof(u32)))
 				break;
 
+			/*
+			 * As with the shared_info attributes: a waiting
+			 * activation must not hold xen_lock, on which a
+			 * vCPU may block from within the kvm->srcu read
+			 * section the memslot update has to wait out.
+			 */
+			mutex_unlock(&vcpu->kvm->arch.xen.xen_lock);
 			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);
+			mutex_lock(&vcpu->kvm->arch.xen.xen_lock);
 		} else {
 			if (data->u.hva == 0) {
 				kvm_gpc_deactivate(&vcpu->arch.xen.vcpu_info_cache);
@@ -988,9 +1053,11 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
 			break;
 		}
 
+		mutex_unlock(&vcpu->kvm->arch.xen.xen_lock);
 		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);
+		mutex_lock(&vcpu->kvm->arch.xen.xen_lock);
 		if (!r)
 			kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
 		break;
@@ -1022,10 +1089,14 @@ 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);
+
+		mutex_unlock(&vcpu->kvm->arch.xen.xen_lock);
 		r = kvm_gpc_activate(&vcpu->arch.xen.runstate_cache,
-				     data->u.gpa, sz1);
-		if (r)
+				     data->u.gpa, sz1, true);
+		if (r) {
+			mutex_lock(&vcpu->kvm->arch.xen.xen_lock);
 			goto deactivate_out;
+		}
 
 		/* Either map the second page, or deactivate the second GPC */
 		if (sz1 >= sz) {
@@ -1034,12 +1105,17 @@ 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);
-			if (r)
+					     data->u.gpa + sz1, sz2, true);
+			if (r) {
+				mutex_lock(&vcpu->kvm->arch.xen.xen_lock);
 				goto deactivate_out;
+			}
 		}
+		mutex_lock(&vcpu->kvm->arch.xen.xen_lock);
 
+		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 +1128,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 +1210,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 +1261,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,13 +1346,14 @@ 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
-		 * timer_pending flag) and there is no need to cancel it.
+		 * 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) {
 			hrtimer_cancel(&vcpu->arch.xen.timer);
@@ -1291,10 +1371,27 @@ 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.
+		 *
+		 * Don't re-arm an undeliverable port: the immediate fire
+		 * would get -EINVAL from the delivery path and destroy
+		 * the timer_expires state just reported to userspace.
 		 */
-		if (vcpu->arch.xen.timer_expires)
-			hrtimer_start_expires(&vcpu->arch.xen.timer,
-					      HRTIMER_MODE_ABS_HARD);
+		if (vcpu->arch.xen.timer_expires &&
+		    !atomic_read(&vcpu->arch.xen.timer_pending) &&
+		    vcpu->arch.xen.timer_virq < kvm_max_evtchn_port(vcpu->kvm))
+			kvm_xen_start_timer(vcpu, vcpu->arch.xen.timer_expires,
+					    false);
 
 		r = 0;
 		break;
@@ -1326,11 +1423,20 @@ int kvm_xen_write_hypercall_page(struct kvm_vcpu *vcpu, u64 data)
 
 		/*
 		 * Re-initialize shared_info to put the wallclock in the
-		 * correct place.
+		 * correct place. The wallclock is a snapshot, written only
+		 * here, and this cannot wait out a memslot update from
+		 * within the vCPU's kvm->srcu read section. If it races
+		 * one (-EAGAIN), just proceed with the stale snapshot; a
+		 * guest changing its own bitness while userspace is
+		 * rearranging memslots has only itself to blame. A real
+		 * failure still fails the WRMSR as it always did.
 		 */
-		if (kvm->arch.xen.shinfo_cache.active &&
-		    kvm_xen_shared_info_init(kvm))
-			r = 1;
+		if (kvm->arch.xen.shinfo_cache.active) {
+			int ret = kvm_xen_shared_info_init(kvm, false);
+
+			if (ret && ret != -EAGAIN)
+				r = 1;
+		}
 	}
 	mutex_unlock(&kvm->arch.xen.xen_lock);
 
@@ -1461,19 +1567,6 @@ static int kvm_xen_hypercall_complete_userspace(struct kvm_vcpu *vcpu)
 	return kvm_xen_hypercall_set_result(vcpu, run->xen.u.hcall.result);
 }
 
-static inline int max_evtchn_port(bool has_64bit_shinfo)
-{
-	if (has_64bit_shinfo)
-		return EVTCHN_2L_NR_CHANNELS;
-	else
-		return COMPAT_EVTCHN_2L_NR_CHANNELS;
-}
-
-static inline int kvm_max_evtchn_port(struct kvm *kvm)
-{
-	return max_evtchn_port(kvm_xen_has_64bit_shinfo(kvm));
-}
-
 static bool wait_pending_event(struct kvm_vcpu *vcpu, bool has_64bit_shinfo,
 			       int nr_ports, evtchn_port_t *ports)
 {
@@ -1775,8 +1868,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 +1937,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 +2034,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 +2059,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 +2087,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 +2147,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 +2168,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 +2242,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 +2471,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 +2485,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 +2494,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 +2523,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 +2544,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..ba23f4e0a4c0f 100644
--- a/include/linux/kvm_host.h
+++ b/include/linux/kvm_host.h
@@ -1456,16 +1456,23 @@ int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
 			 unsigned long len);
 
 /**
- * kvm_gpc_init - initialize gfn_to_pfn_cache.
+ * __kvm_gpc_init - initialize gfn_to_pfn_cache.
  *
  * @gpc:	   struct gfn_to_pfn_cache object.
  * @kvm:	   pointer to kvm instance.
+ * @never_dirty:   the cache never needs to mark its page dirty in its memslot.
  *
  * This sets up a gfn_to_pfn_cache by initializing locks and assigning the
  * immutable attributes.  Note, the cache must be zero-allocated (or zeroed by
- * the caller before init).
+ * the caller before init).  Most callers want the kvm_gpc_init() wrapper.
  */
-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 +1481,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.
@@ -1496,10 +1511,13 @@ int kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long len)
  *                -EINVAL for a mapping which would cross a page boundary.
  *                -EFAULT for an untranslatable guest physical address.
  *
- * The semantics of this function are the same as those of kvm_gpc_activate(). It
- * merely bypasses a layer of address translation.
+ * The semantics of this function are the same as those of kvm_gpc_activate(),
+ * except that an HVA-based cache never consults the memslots and so can
+ * neither return -EAGAIN nor wait: 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 +1542,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 +1556,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 +1997,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..729c0ba9ab4e8 100644
--- a/tools/testing/selftests/kvm/x86/xen_shinfo_test.c
+++ b/tools/testing/selftests/kvm/x86/xen_shinfo_test.c
@@ -350,17 +350,25 @@ static void guest_code(void)
 	p = (struct sched_poll) {
 		.ports = ports,
 		.nr_ports = 1,
-		.timeout = 0
+		/*
+		 * The poll must have a timeout: if the timer event is dropped
+		 * while we are already blocked in the poll, nothing else will
+		 * ever wake us, and the recovery protocol below could never
+		 * run. (As with TEST_POLL_TIMEOUT above, KVM treats the
+		 * timeout as relative.)
+		 */
+		.timeout = 10000000,
 	};
 
 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)

25/3 2026/10/16 23:06 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 23432
							output: 41
							thoughts: 1619
						

Thoughts:
**KMSAN Fuzzing Session Justification**

Okay, so I'm looking at this patch and trying to decide if it warrants a dedicated KMSAN fuzzing session. Let's break it down. My primary concern is uninitialized memory reads or writes, particularly those that could leak sensitive information or lead to kernel panics.

First, I see a significant focus on fixing race conditions and deadlocks between memslot updates and Xen emulation, specifically within the `gfn_to_pfn_cache`. The patch introduces a `wait` parameter to `gpc_activate` and `gpc_refresh`, along with some retry loops. There's also adjustment of `xen_lock` locking and some reordering of operations. Importantly, some `gpc` caches are being marked as `never_dirty`. This is all good, necessary, but I'm checking for memory safety implications of these changes.

Now, let's go over the KMSAN criteria. Does this patch:

1.  **Introduce or modify kernel structures sent to userspace?** I need to look closely for anything that might leak uninitialized memory through `copy_to_user`, `put_user`, netlink, ioctl, etc. I found a potential area of concern with `kvm_xen_vcpu_get_attr` that could be reading uninitialized memory. Let me confirm the parameters of the function to rule this out.

    I need to carefully examine what happens with the `data` structure within `kvm_xen_vcpu_get_attr` since it could be involved in returning data to user space. It seems like it's reading the `timer_expires` from the `vcpu` structure, let me go read the function source code around the line I found in the diff.

    *   Okay, reading the function source code from the line 1267, I can see that this is a GET operation that is reading from kernel data and returning it to the user. I'll need to double check the variables involved to make sure there are no issues with the `data` structure being returned to the user.

2.  **Introduce conditional logic or branching based on potentially uninitialized variables?** The addition of `wait` parameters and retry loops raises a flag. I need to make sure those don't open any doors.

3.  **Involve allocation or initialization of complex data structures where uninitialized fields could be read later?** The changes to the `gfn_to_pfn_cache` are the most relevant here. I need to ensure that the new `never_dirty` flag doesn't create problems.

4.  **Modify bounds checks, lengths, or logic that could allow access to uninitialized bytes of existing buffers?** This is less likely, but I'll still look out for it, especially around the changes to `xen_lock` locking and any memslot operations.

Overall, I think this patch is *reasonably* safe, but I need to dive deeper into the code to completely rule out any KMSAN issues, especially given the `kvm_xen_vcpu_get_attr` I've identified. The extensive changes to locking and retry logic make me cautious. I suspect I might want to start with a targeted KMSAN session on the parts that are the most likely to introduce vulnerabilities. This seems like a good target to review further.



26/3 2026/10/16 23:06 tool read-file
0m Args:
{
  "File": "arch/x86/kvm/xen.c",
  "FirstLine": 1260,
  "LineCount": 45
}

Results:
{
  "Contents": "1260:\t\tdefault:\n1261:\t\t\tbreak;\n1262:\t\t}\n1263:\t\n1264:\t\tmutex_unlock(\u0026vcpu-\u003ekvm-\u003earch.xen.xen_lock);\n1265:\t\treturn r;\n1266:\t}\n1267:\t\n1268:\tint kvm_xen_vcpu_get_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)\n1269:\t{\n1270:\t\tint r = -ENOENT;\n1271:\t\n1272:\t\tmutex_lock(\u0026vcpu-\u003ekvm-\u003earch.xen.xen_lock);\n1273:\t\n1274:\t\tswitch (data-\u003etype) {\n1275:\t\tcase KVM_XEN_VCPU_ATTR_TYPE_VCPU_INFO:\n1276:\t\t\tif (kvm_gpc_is_gpa_active(\u0026vcpu-\u003earch.xen.vcpu_info_cache))\n1277:\t\t\t\tdata-\u003eu.gpa = vcpu-\u003earch.xen.vcpu_info_cache.gpa;\n1278:\t\t\telse\n1279:\t\t\t\tdata-\u003eu.gpa = KVM_XEN_INVALID_GPA;\n1280:\t\t\tr = 0;\n1281:\t\t\tbreak;\n1282:\t\n1283:\t\tcase KVM_XEN_VCPU_ATTR_TYPE_VCPU_INFO_HVA:\n1284:\t\t\tif (kvm_gpc_is_hva_active(\u0026vcpu-\u003earch.xen.vcpu_info_cache))\n1285:\t\t\t\tdata-\u003eu.hva = vcpu-\u003earch.xen.vcpu_info_cache.uhva;\n1286:\t\t\telse\n1287:\t\t\t\tdata-\u003eu.hva = 0;\n1288:\t\t\tr = 0;\n1289:\t\t\tbreak;\n1290:\t\n1291:\t\tcase KVM_XEN_VCPU_ATTR_TYPE_VCPU_TIME_INFO:\n1292:\t\t\tif (vcpu-\u003earch.xen.vcpu_time_info_cache.active)\n1293:\t\t\t\tdata-\u003eu.gpa = vcpu-\u003earch.xen.vcpu_time_info_cache.gpa;\n1294:\t\t\telse\n1295:\t\t\t\tdata-\u003eu.gpa = KVM_XEN_INVALID_GPA;\n1296:\t\t\tr = 0;\n1297:\t\t\tbreak;\n1298:\t\n1299:\t\tcase KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_ADDR:\n1300:\t\t\tif (!sched_info_on()) {\n1301:\t\t\t\tr = -EOPNOTSUPP;\n1302:\t\t\t\tbreak;\n1303:\t\t\t}\n1304:\t\t\tif (vcpu-\u003earch.xen.runstate_cache.active) {\n"
}

27/3 2026/10/16 23:06 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 26571
							output: 41
							thoughts: 26
						

Thoughts:
Okay, let's dive into this `kvm_xen_vcpu_get_attr` function. I remember this one... it's around line 1340, and I'm pretty sure that's where the interesting stuff happens. I need to refresh my memory on what's going on within that section. Let's see what we can find.



28/3 2026/10/16 23:06 tool read-file
0m Args:
{
  "File": "arch/x86/kvm/xen.c",
  "FirstLine": 1340,
  "LineCount": 45
}

Results:
{
  "Contents": "1340:\t\t\tbreak;\n1341:\t\n1342:\t\tcase KVM_XEN_VCPU_ATTR_TYPE_VCPU_ID:\n1343:\t\t\tdata-\u003eu.vcpu_id = vcpu-\u003earch.xen.vcpu_id;\n1344:\t\t\tr = 0;\n1345:\t\t\tbreak;\n1346:\t\n1347:\t\tcase KVM_XEN_VCPU_ATTR_TYPE_TIMER:\n1348:\t\t\t/*\n1349:\t\t\t * Ensure a consistent snapshot of state is captured: a timer\n1350:\t\t\t * which already fired has either been delivered to the\n1351:\t\t\t * corresponding bit in the shared_info, or is reported as\n1352:\t\t\t * still owed (expires_ns != 0, if the shared_info page was\n1353:\t\t\t * unavailable). Purely as an optimisation, if the\n1354:\t\t\t * timer_expires field is zero, that means the timer isn't\n1355:\t\t\t * active (or even in the timer_pending flag) and there is\n1356:\t\t\t * no need to cancel it.\n1357:\t\t\t */\n1358:\t\t\tif (vcpu-\u003earch.xen.timer_expires) {\n1359:\t\t\t\thrtimer_cancel(\u0026vcpu-\u003earch.xen.timer);\n1360:\t\t\t\tkvm_xen_inject_timer_irqs(vcpu);\n1361:\t\t\t}\n1362:\t\n1363:\t\t\tdata-\u003eu.timer.port = vcpu-\u003earch.xen.timer_virq;\n1364:\t\t\tdata-\u003eu.timer.priority = KVM_IRQ_ROUTING_XEN_EVTCHN_PRIO_2LEVEL;\n1365:\t\t\tdata-\u003eu.timer.expires_ns = vcpu-\u003earch.xen.timer_expires;\n1366:\t\n1367:\t\t\t/*\n1368:\t\t\t * The hrtimer may trigger and raise the IRQ immediately,\n1369:\t\t\t * while the returned state causes it to be set up and\n1370:\t\t\t * raised again on the destination system after migration.\n1371:\t\t\t * That's fine, as the guest won't even have had a chance\n1372:\t\t\t * to run and handle the interrupt. Asserting an already\n1373:\t\t\t * pending event channel is idempotent.\n1374:\t\t\t *\n1375:\t\t\t * Don't re-arm if the flush above failed transiently and\n1376:\t\t\t * left the timer pending: delivery is owned by the retry\n1377:\t\t\t * on the guest entry path, and an immediate hrtimer fire\n1378:\t\t\t * would race it — the callback's timer_pending suppression\n1379:\t\t\t * check is not serialized against the entry path, so a\n1380:\t\t\t * late callback could re-assert a port the entry path had\n1381:\t\t\t * already delivered and the guest already consumed.\n1382:\t\t\t *\n1383:\t\t\t * An expiry already in the past fires immediately: the\n1384:\t\t\t * event is still owed.\n"
}

29/3 2026/10/16 23:06 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 27509
							output: 25
							thoughts: 71
						

Thoughts:
Okay, here's my understanding, tailored for an expert audience, as if it were my own thought process:

**Diving into kvm_xen_vcpu_get_attr**

Alright, I'm working with `kvm_xen_vcpu_get_attr` and noticing some familiar setup within the function. Specifically, `data->u.timer.port`, `priority`, and `expires_ns` are being assigned values, looking just as they should, as I'd expect given the context. My immediate next move is to understand where this function is being invoked. I'll need to trace its call sites to fully grasp its role within the larger system.

Time to reach for the trusty grep command to identify the callers of `kvm_xen_vcpu_get_attr`. That'll be my starting point to understand the interactions.



30/3 2026/10/16 23:06 tool grepper
0m Args:
{
  "Expression": "kvm_xen_vcpu_get_attr"
}

Results:
{
  "Output": "arch/x86/kvm/x86.c=3430=long kvm_arch_vcpu_ioctl(struct file *filp,\n--\narch/x86/kvm/x86.c-3834-\t\t\tgoto out;\narch/x86/kvm/x86.c:3835:\t\tr = kvm_xen_vcpu_get_attr(vcpu, \u0026xva);\narch/x86/kvm/x86.c-3836-\t\tif (!r \u0026\u0026 copy_to_user(argp, \u0026xva, sizeof(xva)))\n--\narch/x86/kvm/xen.c=993=int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)\n--\narch/x86/kvm/xen.c-1267-\narch/x86/kvm/xen.c:1268:int kvm_xen_vcpu_get_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)\narch/x86/kvm/xen.c-1269-{\n--\narch/x86/kvm/xen.h=23=int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data);\narch/x86/kvm/xen.h:24:int kvm_xen_vcpu_get_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data);\narch/x86/kvm/xen.h-25-int kvm_xen_hvm_set_attr(struct kvm *kvm, struct kvm_xen_hvm_attr *data);\n"
}

31/3 2026/10/16 23:07 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 28261
							output: 43
							thoughts: 30
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience, presented in the first person:

**Analyzing XVA Handling within KVM/x86**

Alright, let's dive in. I need to refresh my memory on how XVA – specifically, the implementation details within the x86 architecture – is managed within the KVM subsystem. Time to navigate to `arch/x86/kvm/x86.c:3834`. I'm going to pinpoint that specific line and its surrounding context. I anticipate finding the core logic there, likely dealing with context switching, instruction emulation, or perhaps interrupt handling related to XVA features. I'll be looking for any hints on how the hardware interactions are virtualized, any special handling for guest-to-host interactions regarding XVA, or potential performance considerations. My primary goal here is to understand the control flow and data structures involved, ensuring everything is as expected within the KVM framework. I'm prepared to trace calls, cross-reference with related files, and really get into the weeds of this specific section of the code. This should refresh my understanding of where XVA features may be used and where potential bottlenecks or subtle edge cases may occur.



32/3 2026/10/16 23:07 tool read-file
0m Args:
{
  "File": "arch/x86/kvm/x86.c",
  "FirstLine": 3825,
  "LineCount": 20
}

Results:
{
  "Contents": "3825:\t\t\tr = kvm_ioctl_get_supported_hv_cpuid(vcpu, argp);\n3826:\t\t\tbreak;\n3827:\t#endif\n3828:\t#ifdef CONFIG_KVM_XEN\n3829:\t\tcase KVM_XEN_VCPU_GET_ATTR: {\n3830:\t\t\tstruct kvm_xen_vcpu_attr xva;\n3831:\t\n3832:\t\t\tr = -EFAULT;\n3833:\t\t\tif (copy_from_user(\u0026xva, argp, sizeof(xva)))\n3834:\t\t\t\tgoto out;\n3835:\t\t\tr = kvm_xen_vcpu_get_attr(vcpu, \u0026xva);\n3836:\t\t\tif (!r \u0026\u0026 copy_to_user(argp, \u0026xva, sizeof(xva)))\n3837:\t\t\t\tr = -EFAULT;\n3838:\t\t\tbreak;\n3839:\t\t}\n3840:\t\tcase KVM_XEN_VCPU_SET_ATTR: {\n3841:\t\t\tstruct kvm_xen_vcpu_attr xva;\n3842:\t\n3843:\t\t\tr = -EFAULT;\n3844:\t\t\tif (copy_from_user(\u0026xva, argp, sizeof(xva)))\n"
}

33/3 2026/10/16 23:07 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 28942
							output: 23
							thoughts: 1003
						

Thoughts:
**Analyzing Potential Data Races and Initialization Issues**

Okay, let's break this down. My initial concern was centered around potential data races and uninitialized data, specifically regarding the interaction between `copy_from_user` and `kvm_xen_vcpu_get_attr`.  The code copies data into `xva` fully *before* `kvm_xen_vcpu_get_attr` sets specific fields.  The good news is that I've confirmed that the way `data` is written within `kvm_xen_vcpu_get_attr` hasn't changed. That's a point in the right direction.

Now, let's pivot and examine the other code changes. I'm focusing on the recent modifications in `pfncache.c`, `xen.c`, `x86.c`, and `msrs.c`. The addition of `bool never_dirty;` to `struct gfn_to_pfn_cache` in `include/linux/kvm_types.h` caught my eye. This is interesting, as it indicates a new optimization or behavior related to page frame number caching.

How is this `struct gfn_to_pfn_cache` allocated and initialized? I'm going through the initialization paths now.  `__kvm_gpc_init` is the key, and it explicitly sets `gpc->never_dirty = never_dirty;`.  Looking at the callers, `kvm_gpc_init` passes `false`, while `kvm_xen_init_vcpu` and `kvm_xen_init_vm` pass `true`. This means `never_dirty` is *always* initialized, which is what I wanted to confirm.

Next, I'm analyzing `__kvm_xen_set_evtchn_fast` in detail.  Here I am paying particular attention to potential data races or incorrect assumptions. I see that all variables (`inject_upcall`, `kick_vcpu`) are properly initialized.  `vi_pending_sel_ofs` is assigned based on `has_64bit_shinfo`. It looks like the critical section is protected with a read lock, and the code checks with `kvm_gpc_check` if the cache is valid for the operation. The `GEN_BINARY_RMWcc` macro seems to be used to perform an atomic read-modify-write operation.  The `kick_vcpu` and `inject_upcall` flags look sound.  Overall, nothing jumps out at me as immediately problematic here.

Finally, I'm examining `kvm_xen_inject_timer_irqs`.  My focus is on the `struct kvm_xen_evtchn e` that is being passed to `kvm_xen_set_evtchn`. Wait a minute... I need to refresh my memory on what fields exactly are in that structure! Let me search for the definition of `struct kvm_xen_evtchn` in the codebase and check its members.



34/3 2026/10/16 23:07 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"
}

35/3 2026/10/16 23:07 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 30720
							output: 38
							thoughts: 27
						

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

**Diving into the KVM/Xen Event Channel Structure**

Alright, let's get down to brass tacks. I need to understand how the KVM/Xen integration handles event channels. My initial thought is, let's jump straight to the source. Specifically, I want to refresh my memory and examine the `struct kvm_xen_evtchn` definition within `include/linux/kvm_host.h`. I'm going to start with a line-by-line review of the structure definition. I'm looking for details regarding its internal members, particularly the fields relating to interrupt numbers, guest and host mappings, the overall mechanism of event delivery, and any potential synchronization primitives. I'm keen to understand how this structure facilitates the communication between the KVM guest and the Xen hypervisor, especially how events from the emulated hardware within the KVM guest are propagated. I'll need to then quickly consider how this structure relates to the larger KVM architecture and Xen integration. Understanding this event channel structure is crucial for debugging and optimizing interactions between the two virtualization layers.



36/3 2026/10/16 23:07 tool read-file
0m Args:
{
  "File": "include/linux/kvm_host.h",
  "FirstLine": 660,
  "LineCount": 15
}

Results:
{
  "Contents": " 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"
}

37/3 2026/10/16 23:07 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 31263
							output: 41
							thoughts: 718
						

Thoughts:
**Analyzing Xen Event Channel Injection**

Okay, so I'm digging into this Xen event channel stuff in KVM. My immediate focus is on how timer interrupts are being injected. I see that the `kvm_xen_evtchn` structure, with its `port`, `vcpu_id`, `vcpu_idx`, and `priority` fields, is fully initialized when dealing with timer interrupts. That's good; no missing pieces. The existing code already set these fields before the patch, which is reassuring.

Now, let's trace this. `kvm_xen_inject_timer_irqs` uses `kvm_xen_set_evtchn`. And what is the effect of the changes to `kvm_xen_set_evtchn`? We want to know if everything is being properly handled. The crucial part is the `kvm_xen_hcall_evtchn_send` function, which handles the actual hypercall.

I see a `struct evtchn_send` which is just a `uint32_t`, alright. The important bit is that the return code `*r` will be set to either 0 on success or `-EFAULT` if `kvm_read_guest_virt` fails.

Now, in `kvm_xen_hypercall`, if `ret == 0` (success from `kvm_xen_hcall_evtchn_send`), `handled` becomes `1`. Also `*r` was modified inside `kvm_xen_hcall_evtchn_send`. If `ret == -ENOENT`, the hypercall isn't handled. So the question is: when `handled` is `true`, what happens next? I need to check the surrounding code in `arch/x86/kvm/xen.c`, specifically around the `kvm_xen_hypercall` function to understand the complete execution flow.



38/3 2026/10/16 23:08 tool read-file
0m Args:
{
  "File": "arch/x86/kvm/xen.c",
  "FirstLine": 1880,
  "LineCount": 40
}

Results:
{
  "Contents": "1880:\t\t\t\t * way back in, letting the update complete.\n1881:\t\t\t\t */\n1882:\t\t\t\tif (ret == -EAGAIN)\n1883:\t\t\t\t\treturn 1;\n1884:\t\t\t\thandled = !ret;\n1885:\t\t\t}\n1886:\t\t\tbreak;\n1887:\t\tcase __HYPERVISOR_sched_op:\n1888:\t\t\thandled = kvm_xen_hcall_sched_op(vcpu, is_64bit, params[0],\n1889:\t\t\t\t\t\t\t params[1], \u0026r);\n1890:\t\t\tbreak;\n1891:\t\tcase __HYPERVISOR_vcpu_op:\n1892:\t\t\thandled = kvm_xen_hcall_vcpu_op(vcpu, is_64bit, params[0], params[1],\n1893:\t\t\t\t\t\t\tparams[2], \u0026r);\n1894:\t\t\tbreak;\n1895:\t\tcase __HYPERVISOR_set_timer_op: {\n1896:\t\t\tu64 timeout = params[0];\n1897:\t\t\t/* In 32-bit mode, the 64-bit timeout is in two 32-bit params. */\n1898:\t\t\tif (!is_64bit)\n1899:\t\t\t\ttimeout |= params[1] \u003c\u003c 32;\n1900:\t\t\thandled = kvm_xen_hcall_set_timer_op(vcpu, timeout, \u0026r);\n1901:\t\t\tbreak;\n1902:\t\t}\n1903:\t\tdefault:\n1904:\t\t\tbreak;\n1905:\t\t}\n1906:\t\n1907:\t\tif (handled)\n1908:\t\t\treturn kvm_xen_hypercall_set_result(vcpu, r);\n1909:\t\n1910:\thandle_in_userspace:\n1911:\t\tvcpu-\u003erun-\u003eexit_reason = KVM_EXIT_XEN;\n1912:\t\tvcpu-\u003erun-\u003exen.type = KVM_EXIT_XEN_HCALL;\n1913:\t\tvcpu-\u003erun-\u003exen.u.hcall.longmode = is_64bit;\n1914:\t\tvcpu-\u003erun-\u003exen.u.hcall.cpl = cpl;\n1915:\t\tvcpu-\u003erun-\u003exen.u.hcall.input = input;\n1916:\t\tvcpu-\u003erun-\u003exen.u.hcall.params[0] = params[0];\n1917:\t\tvcpu-\u003erun-\u003exen.u.hcall.params[1] = params[1];\n1918:\t\tvcpu-\u003erun-\u003exen.u.hcall.params[2] = params[2];\n1919:\t\tvcpu-\u003erun-\u003exen.u.hcall.params[3] = params[3];\n"
}

39/3 2026/10/16 23:08 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 33160
							output: 42
							thoughts: 41
						

Thoughts:
Okay, here's my interpretation of that thought process, from an expert's perspective:

**Debugging a Potential Hypercall Error**

Alright, so I'm digging into this `kvm_xen_hypercall` function. I see that the return value, which is stored in `r`, has been initialized to `-ENOSYS`.  That screams "unimplemented" or "not supported" to me.  A negative return value is a pretty standard way to signal an error, and `-ENOSYS` specifically means "Function not implemented".

Now, I need to figure out *why* we're hitting this.  The first thing I'll do is trace where `r` is actually defined. I need to understand where and how the value of `r` is set, and whether it's ever changed before this point.  Is this a default value? Is it set by some earlier hypercall or some other process?  I'll trace the initialization to find out how `r` is set. The goal is to see where the function starts, and understand what happens to `r` during execution. If `r` isn't updated, there's a problem, and I'll see where the error gets caught.



40/3 2026/10/16 23:08 tool grepper
0m Args:
{
  "Expression": "int kvm_xen_hypercall\\(",
  "PathPrefixes": [
    "arch/x86/kvm/xen.c"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/xen.c=1801=static bool kvm_xen_hcall_set_timer_op(struct kvm_vcpu *vcpu, uint64_t timeout,\n--\narch/x86/kvm/xen.c-1815-\narch/x86/kvm/xen.c:1816:int kvm_xen_hypercall(struct kvm_vcpu *vcpu)\narch/x86/kvm/xen.c-1817-{\n"
}

41/3 2026/10/16 23:08 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 33647
							output: 41
							thoughts: 29
						

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

**Analyzing the KVM Xen Hypercall Entry Point**

Alright, let's dive into the guts of `kvm_xen_hypercall` in `arch/x86/kvm/xen.c`. I need to refresh my memory on how KVM interfaces with the Xen hypervisor, specifically where the hypercall entry point is defined. Understanding this is crucial for tracing execution flow when interacting with Xen paravirtualized domains from within a KVM guest. I want to see how the code handles the transition between the KVM and Xen worlds, and what arguments are passed during the call. I'm especially interested in whether there are any performance considerations or potential bottlenecks in this section. I'm anticipating that this function will be the focal point for any Xen-specific operations KVM needs to handle. I wonder if there are any quirks or workarounds in this code to maintain compatibility and efficiency. Let's see if this function is responsible for trapping to the hypervisor, or simply sets up the appropriate context for a later trap. It will also be worthwhile to understand how this is used within the overall KVM architecture to support nested virtualization.



42/3 2026/10/16 23:08 tool read-file
0m Args:
{
  "File": "arch/x86/kvm/xen.c",
  "FirstLine": 1816,
  "LineCount": 40
}

Results:
{
  "Contents": "1816:\tint kvm_xen_hypercall(struct kvm_vcpu *vcpu)\n1817:\t{\n1818:\t\tbool is_64bit;\n1819:\t\tu64 input, params[6], r = -ENOSYS;\n1820:\t\tbool handled = false;\n1821:\t\tu8 cpl;\n1822:\t\n1823:\t\t/* Hyper-V hypercalls get bit 31 set in EAX */\n1824:\t\tif ((kvm_rax_read_raw(vcpu) \u0026 0x80000000) \u0026\u0026\n1825:\t\t    kvm_hv_hypercall_enabled(vcpu))\n1826:\t\t\treturn kvm_hv_hypercall(vcpu);\n1827:\t\n1828:\t\tis_64bit = is_64_bit_hypercall(vcpu);\n1829:\t\tif (!is_64bit) {\n1830:\t\t\tinput = kvm_eax_read(vcpu);\n1831:\t\t\tparams[0] = kvm_ebx_read(vcpu);\n1832:\t\t\tparams[1] = kvm_ecx_read(vcpu);\n1833:\t\t\tparams[2] = kvm_edx_read(vcpu);\n1834:\t\t\tparams[3] = kvm_esi_read(vcpu);\n1835:\t\t\tparams[4] = kvm_edi_read(vcpu);\n1836:\t\t\tparams[5] = kvm_ebp_read(vcpu);\n1837:\t\t}\n1838:\t\telse {\n1839:\t#ifdef CONFIG_X86_64\n1840:\t\t\tinput = (u64)kvm_rax_read_raw(vcpu);\n1841:\t\t\tparams[0] = (u64)kvm_rdi_read_raw(vcpu);\n1842:\t\t\tparams[1] = (u64)kvm_rsi_read_raw(vcpu);\n1843:\t\t\tparams[2] = (u64)kvm_rdx_read_raw(vcpu);\n1844:\t\t\tparams[3] = (u64)kvm_r10_read_raw(vcpu);\n1845:\t\t\tparams[4] = (u64)kvm_r8_read_raw(vcpu);\n1846:\t\t\tparams[5] = (u64)kvm_r9_read_raw(vcpu);\n1847:\t#else\n1848:\t\t\tKVM_BUG_ON(1, vcpu-\u003ekvm);\n1849:\t\t\treturn -EIO;\n1850:\t#endif\n1851:\t\t}\n1852:\t\tcpl = kvm_x86_call(get_cpl)(vcpu);\n1853:\t\ttrace_kvm_xen_hypercall(cpl, input, params[0], params[1], params[2],\n1854:\t\t\t\t\tparams[3], params[4], params[5]);\n1855:\t\n"
}

43/3 2026/10/16 23:08 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 34777
							output: 400
							thoughts: 1695
						

Thoughts:
**KMSAN Assessment: NeedsKMSAN = false**

Okay, let's break this down. My initial `r` value is `-ENOSYS`, but that's not the relevant bit. I need to determine if this patch necessitates KMSAN. My expertise tells me that KMSAN is reserved for identifying uninitialized memory reads or information leaks. So I'll go through the patch logic step by step to see if any of the changes introduce such risks.

First, I examine the changes within `pfncache.c`. I note retry logic is added for transient errors using `-EAGAIN` related to invalid memslots. This involves mutexes and SRCU read locks, which has me thinking about potential deadlocks or race conditions. I also see loops with `cond_resched()`, which could lead to livelocks. The new logic is designed to improve concurrency between memslot updates and Xen emulation, specifically focusing on `gfn_to_pfn_cache` within SRCU sections. I see lockdep annotations, which is good. The introduction of `never_dirty` seems straightforward, but I need to confirm its initialization and usage.

Moving onto `include/linux/kvm_host.h`, I review `kvm_gpc_mark_dirty_in_slot`. The check for `!gpc->memslot || gpc->never_dirty` is important. I need to be sure that `never_dirty` is initialized correctly. Looking at the documentation, the Xen shared info page and vcpu_info area are always assumed to be dirty, which seems separate from the patch and not relevant to my immediate KMSAN question.

Then, I check if the patch modifies any kernel-to-user copies. I see `kvm_xen_vcpu_get_attr` which copies from user, updates and then copies back. This function is interesting because it copies user data. I focus on this to confirm that *existing* fields are only set, and that no new uninitialized fields are sent to userspace.

Next, I assess whether uninitialized memory is read or used in any conditional logic, allocation, deallocation, bounds checks, or data length manipulations. Nope, no changes indicate a risk of uninitialized memory reads or information leaks. The risks are primarily centered on concurrency, lock management, and potential livelocks or logical bugs, but these fall within the scope of what KASAN, LOCKDEP, and standard debuggers catch. I see nothing introduced that requires KMSAN. All new variables/structures added are simple primitives (bools, ints, pointers), and are initialized.

Finally, I revisit the KMSAN guidelines, confirming that I'm only supposed to set `NeedsKMSAN=true` if uninitialized memory risks are *only* detectable by KMSAN. Since these changes introduce race conditions, deadlocks, and livelocks, but nothing that's not catchable by LOCKDEP and standard debuggers, I'm confident in setting `NeedsKMSAN = false`. I also note that the reasoning should explain the analysis: the patch primarily focuses on concurrency with initialization of new variables, and no new kernel-to-user copies or branching on uninitialized memory is introduced. Therefore, I believe the risk analysis is robust and no KMSAN fuzzing is necessary.



44/3 2026/10/16 23:08 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch series addresses deadlock and race conditions between KVM memslot updates and Xen emulation (specifically gfn_to_pfn_cache) when executed within SRCU read sections. The main modifications include:\n1. Introducing an -EAGAIN return when a memslot is transiently invalid (under churn) and adding a retry loop with a `wait` parameter to `kvm_gpc_activate()` and `kvm_gpc_refresh()`.\n2. Restructuring lock nesting around `xen_lock` and GPC read locks to ensure that memslot waits do not hold locks that could deadlock against SRCU readers.\n3. Deferring guest TLB flush requests (`KVM_REQ_TLB_FLUSH_GUEST`) during `record_steal_time()` and handling them on guest entry.\n4. Adding a `never_dirty` flag to `struct gfn_to_pfn_cache` to skip dirty page logging for Xen shared_info and vcpu_info.\n\nNone of these changes introduce or modify uninitialized memory access risks:\n- All new struct fields (`gpc-\u003enever_dirty`) and local variables (`inject_upcall`, `kick_vcpu`, `wait`, `rc`, etc.) are explicitly initialized before use.\n- No kernel-to-user memory transfers are modified in a way that risks uninitialized data or padding leaks (`kvm_xen_vcpu_get_attr` operates on an `xva` buffer populated by `copy_from_user`).\n- The hazards associated with this patch involve lock ordering, deadlocks, and race conditions during concurrent memslot updates and Xen event delivery. These are monitored by LOCKDEP and standard KASAN configurations. KMSAN does not provide additional detection capability here.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch series addresses deadlock and race conditions between KVM memslot updates and Xen emulation (specifically gfn_to_pfn_cache) when executed within SRCU read sections. The main modifications include:\n1. Introducing an -EAGAIN return when a memslot is transiently invalid (under churn) and adding a retry loop with a `wait` parameter to `kvm_gpc_activate()` and `kvm_gpc_refresh()`.\n2. Restructuring lock nesting around `xen_lock` and GPC read locks to ensure that memslot waits do not hold locks that could deadlock against SRCU readers.\n3. Deferring guest TLB flush requests (`KVM_REQ_TLB_FLUSH_GUEST`) during `record_steal_time()` and handling them on guest entry.\n4. Adding a `never_dirty` flag to `struct gfn_to_pfn_cache` to skip dirty page logging for Xen shared_info and vcpu_info.\n\nNone of these changes introduce or modify uninitialized memory access risks:\n- All new struct fields (`gpc-\u003enever_dirty`) and local variables (`inject_upcall`, `kick_vcpu`, `wait`, `rc`, etc.) are explicitly initialized before use.\n- No kernel-to-user memory transfers are modified in a way that risks uninitialized data or padding leaks (`kvm_xen_vcpu_get_attr` operates on an `xva` buffer populated by `copy_from_user`).\n- The hazards associated with this patch involve lock ordering, deadlocks, and race conditions during concurrent memslot updates and Xen event delivery. These are monitored by LOCKDEP and standard KASAN configurations. KMSAN does not provide additional detection capability here.",
  "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)