AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/11/06 06:25 flow patch-triage
36m Args:
null

Results:
{
  "EnableConfigs": [
    "KVM",
    "KVM_INTEL",
    "KVM_AMD"
  ],
  "FocusSymbols": [
    "memslot_rmap_alloc",
    "memslot_rmap_free",
    "gfn_to_rmap_alloc",
    "slot_rmap_walk_next",
    "shadow_mmu_split_huge_page",
    "kvm_mmu_slot_try_split_huge_pages",
    "kvm_mmu_rmaps_stat_show",
    "kvm_mmu_rmaps_stat_level"
  ],
  "KMSANReasoning": "The patch transitions KVM shadow MMU rmap tracking from monolithic arrays to on-demand allocated chunk pages (each holding KVM_RMAP_CHUNK_NR_HEADS rmap heads).\n\nAnalysis of memory initialization and user-facing data:\n1. The chunk directories (`slot-\u003earch.rmap[i]`) are allocated using `kvcalloc()`, which zeroes all chunk pointers.\n2. The rmap chunk pages are allocated via `kvm_mmu_memory_cache_alloc()` from `mmu_rmap_chunk_cache` and `split_rmap_chunk_cache`, both of which are explicitly configured with `gfp_zero = __GFP_ZERO`, ensuring that every newly allocated chunk is zero-filled.\n3. The fallback `kvm_empty_rmap_head` is declared as static storage and thus is zero-initialized.\n4. The rmaps stat debugfs handler allocates its counting buckets with `kcalloc()`.\n5. No uninitialized memory, struct fields, or padding are exposed or copied to user space.\n\nPotential bugs in this patch involve chunk indexing arithmetic, iterator walk logic, concurrent lockless chunk installation, or chunk deallocation (`free_page`), which could lead to out-of-bounds accesses, use-after-free, or synchronization errors. These risks are effectively detected by KASAN, LOCKDEP, and page debugging tools. Because there are no uninitialized memory access or info-leak risks, a dedicated KMSAN fuzzing session is not justified.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch converts KVM x86 shadow MMU reverse mapping (rmap) arrays into sparse two-level chunk directories allocated on demand. This touches core KVM memory management logic, introducing lockless chunk publication (smp_store_release/READ_ONCE), chunk-skipping iteration in slot_rmap_walk_next, rmap chunk caching during huge page splitting, and new memslot rmap allocation and deallocation paths. This code is fully reachable via KVM ioctls and debugfs, making it a high-value target for fuzzing.",
  "WorthFuzzing": true
}

1/1 2026/11/06 06:25 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit 5315a724060f567610297263a0938d976c4486c6\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Fri Nov 6 06:25:41 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/arch/x86/include/asm/kvm_host.h b/arch/x86/include/asm/kvm_host.h\nindex 0378577d9d8bbf..4cc00dc83aba4d 100644\n--- a/arch/x86/include/asm/kvm_host.h\n+++ b/arch/x86/include/asm/kvm_host.h\n@@ -431,6 +431,8 @@ struct kvm_rmap_head {\n \tatomic_long_t val;\n };\n \n+#define KVM_RMAP_CHUNK_NR_HEADS\t(PAGE_SIZE / sizeof(struct kvm_rmap_head))\n+\n struct kvm_pio_request {\n \tunsigned long count;\n \tint in;\n@@ -785,6 +787,7 @@ struct kvm_vcpu_arch {\n \tu64 pdptrs[4]; /* pae */\n \n \tstruct kvm_mmu_memory_cache mmu_pte_list_desc_cache;\n+\tstruct kvm_mmu_memory_cache mmu_rmap_chunk_cache;\n \tstruct kvm_mmu_memory_cache mmu_shadow_page_cache;\n \tstruct kvm_mmu_memory_cache mmu_shadowed_info_cache;\n \tstruct kvm_mmu_memory_cache mmu_page_header_cache;\n@@ -1044,7 +1047,13 @@ struct kvm_lpage_info {\n };\n \n struct kvm_arch_memory_slot {\n-\tstruct kvm_rmap_head *rmap[KVM_NR_PAGE_SIZES];\n+\t/*\n+\t * Per-level directories of rmap chunks, each chunk holding\n+\t * KVM_RMAP_CHUNK_NR_HEADS rmap heads.  Chunks are allocated when KVM\n+\t * adds the first SPTE to a head in the chunk's range.  A NULL chunk\n+\t * means all of its heads are empty.\n+\t */\n+\tstruct kvm_rmap_head **rmap[KVM_NR_PAGE_SIZES];\n \tstruct kvm_lpage_info *lpage_info[KVM_NR_PAGE_SIZES - 1];\n \tunsigned short *gfn_write_track;\n };\n@@ -1418,6 +1427,17 @@ struct kvm_arch {\n #define SPLIT_DESC_CACHE_MIN_NR_OBJECTS (SPTE_ENT_PER_PAGE + 1)\n \tstruct kvm_mmu_memory_cache split_desc_cache;\n \n+\t/*\n+\t * Memory cache used to allocate rmap chunks while splitting huge\n+\t * pages.  The rmap heads of the lower level leaf SPTEs of one huge\n+\t * page are contiguous, but span two chunks if the memslot's base gfn\n+\t * is not aligned to the chunk size.\n+\t *\n+\t * Protected by kvm-\u003eslots_lock.\n+\t */\n+#define SPLIT_RMAP_CHUNK_CACHE_NR_OBJECTS 2\n+\tstruct kvm_mmu_memory_cache split_rmap_chunk_cache;\n+\n \tgfn_t gfn_direct_bits;\n \tint mirror_root_level;\n \ndiff --git a/arch/x86/kvm/debugfs.c b/arch/x86/kvm/debugfs.c\nindex 0074a56e45b44b..0cdb1ef1b18416 100644\n--- a/arch/x86/kvm/debugfs.c\n+++ b/arch/x86/kvm/debugfs.c\n@@ -86,16 +86,43 @@ void kvm_arch_create_vcpu_debugfs(struct kvm_vcpu *vcpu, struct dentry *debugfs_\n \n static const char *kvm_lpage_str[KVM_NR_PAGE_SIZES] = { \"4K\", \"2M\", \"1G\" };\n \n+static void kvm_mmu_rmaps_stat_level(struct kvm_memory_slot *slot, int level,\n+\t\t\t\t     unsigned int *cur)\n+{\n+\tstruct kvm_rmap_head **rmap = slot-\u003earch.rmap[level - PG_LEVEL_4K];\n+\tunsigned long lpages = kvm_mmu_slot_lpages(slot, level);\n+\tstruct kvm_rmap_head *chunk;\n+\tunsigned long l, nr;\n+\tunsigned int index;\n+\n+\tfor (l = 0; l \u003c lpages; l += nr) {\n+\t\tnr = min(lpages - l, KVM_RMAP_CHUNK_NR_HEADS);\n+\t\tchunk = rmap[l / KVM_RMAP_CHUNK_NR_HEADS];\n+\n+\t\t/* An unallocated chunk holds only empty rmaps. */\n+\t\tif (!chunk) {\n+\t\t\tcur[0] += nr;\n+\t\t\tcontinue;\n+\t\t}\n+\n+\t\tfor (index = 0; index \u003c nr; index++) {\n+\t\t\tunsigned int bucket = fls(pte_list_count(\u0026chunk[index]));\n+\n+\t\t\tif (WARN_ON_ONCE(bucket \u003e= RMAP_LOG_SIZE))\n+\t\t\t\tbucket = RMAP_LOG_SIZE - 1;\n+\t\t\tcur[bucket]++;\n+\t\t}\n+\t}\n+}\n+\n static int kvm_mmu_rmaps_stat_show(struct seq_file *m, void *v)\n {\n-\tstruct kvm_rmap_head *rmap;\n \tstruct kvm *kvm = m-\u003eprivate;\n \tstruct kvm_memory_slot *slot;\n \tstruct kvm_memslots *slots;\n-\tunsigned int lpage_size, index;\n \t/* Still small enough to be on the stack */\n \tunsigned int *log[KVM_NR_PAGE_SIZES], *cur;\n-\tint i, j, k, l, ret;\n+\tint i, j, k, ret;\n \n \tif (!kvm_memslots_have_rmaps(kvm))\n \t\treturn 0;\n@@ -116,17 +143,8 @@ static int kvm_mmu_rmaps_stat_show(struct seq_file *m, void *v)\n \n \t\tslots = __kvm_memslots(kvm, i);\n \t\tkvm_for_each_memslot(slot, bkt, slots)\n-\t\t\tfor (k = 0; k \u003c KVM_NR_PAGE_SIZES; k++) {\n-\t\t\t\trmap = slot-\u003earch.rmap[k];\n-\t\t\t\tlpage_size = kvm_mmu_slot_lpages(slot, k + 1);\n-\t\t\t\tcur = log[k];\n-\t\t\t\tfor (l = 0; l \u003c lpage_size; l++) {\n-\t\t\t\t\tindex = fls(pte_list_count(\u0026rmap[l]));\n-\t\t\t\t\tif (WARN_ON_ONCE(index \u003e= RMAP_LOG_SIZE))\n-\t\t\t\t\t\tindex = RMAP_LOG_SIZE - 1;\n-\t\t\t\t\tcur[index]++;\n-\t\t\t\t}\n-\t\t\t}\n+\t\t\tfor (k = 0; k \u003c KVM_NR_PAGE_SIZES; k++)\n+\t\t\t\tkvm_mmu_rmaps_stat_level(slot, k + 1, log[k]);\n \t}\n \n \twrite_unlock(\u0026kvm-\u003emmu_lock);\ndiff --git a/arch/x86/kvm/mmu/mmu.c b/arch/x86/kvm/mmu/mmu.c\nindex f4b12d6aef5593..1b958f66764c15 100644\n--- a/arch/x86/kvm/mmu/mmu.c\n+++ b/arch/x86/kvm/mmu/mmu.c\n@@ -612,6 +612,17 @@ static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)\n \t\t\t\t       1 + PT64_ROOT_MAX_LEVEL + PTE_PREFETCH_NUM);\n \tif (r)\n \t\treturn r;\n+\t/*\n+\t * 1 rmap chunk for the faulting gfn and 1 per prefetched gfn.  Cap the\n+\t * cache at that, as each object is a page.\n+\t */\n+\tif (kvm_memslots_have_rmaps(vcpu-\u003ekvm)) {\n+\t\tr = __kvm_mmu_topup_memory_cache(\u0026vcpu-\u003earch.mmu_rmap_chunk_cache,\n+\t\t\t\t\t\t 1 + PTE_PREFETCH_NUM,\n+\t\t\t\t\t\t 1 + PTE_PREFETCH_NUM);\n+\t\tif (r)\n+\t\t\treturn r;\n+\t}\n \tif (kvm_has_mirrored_tdp(vcpu-\u003ekvm)) {\n \t\tr = kvm_mmu_topup_memory_cache(\u0026vcpu-\u003earch.mmu_external_spt_cache,\n \t\t\t\t\t       PT64_ROOT_MAX_LEVEL);\n@@ -635,6 +646,7 @@ static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)\n static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)\n {\n \tkvm_mmu_free_memory_cache(\u0026vcpu-\u003earch.mmu_pte_list_desc_cache);\n+\tkvm_mmu_free_memory_cache(\u0026vcpu-\u003earch.mmu_rmap_chunk_cache);\n \tkvm_mmu_free_memory_cache(\u0026vcpu-\u003earch.mmu_shadow_page_cache);\n \tkvm_mmu_free_memory_cache(\u0026vcpu-\u003earch.mmu_shadowed_info_cache);\n \tkvm_mmu_free_memory_cache(\u0026vcpu-\u003earch.mmu_external_spt_cache);\n@@ -1236,13 +1248,65 @@ unsigned int pte_list_count(struct kvm_rmap_head *rmap_head)\n \treturn desc-\u003etail_count + desc-\u003espte_count;\n }\n \n+/*\n+ * Returned by gfn_to_rmap() for heads in a chunk that hasn't been allocated.\n+ * Readers see an empty rmap, and only __rmap_add() writes to a head that may\n+ * be empty, after allocating its chunk.\n+ */\n+static struct kvm_rmap_head kvm_empty_rmap_head;\n+\n+static struct kvm_rmap_head **\n+rmap_chunkp(const struct kvm_memory_slot *slot, int level, unsigned long idx)\n+{\n+\treturn \u0026slot-\u003earch.rmap[level - PG_LEVEL_4K][idx / KVM_RMAP_CHUNK_NR_HEADS];\n+}\n+\n+/* Returns NULL if the chunk holding the head hasn't been allocated. */\n+static struct kvm_rmap_head *__idx_to_rmap(const struct kvm_memory_slot *slot,\n+\t\t\t\t\t   int level, unsigned long idx)\n+{\n+\tstruct kvm_rmap_head *chunk;\n+\n+\t/*\n+\t * Lockless walkers can observe a chunk being installed.  Pairs with\n+\t * the smp_store_release() in gfn_to_rmap_alloc().\n+\t */\n+\tchunk = READ_ONCE(*rmap_chunkp(slot, level, idx));\n+\tif (!chunk)\n+\t\treturn NULL;\n+\n+\treturn \u0026chunk[idx % KVM_RMAP_CHUNK_NR_HEADS];\n+}\n+\n static struct kvm_rmap_head *gfn_to_rmap(gfn_t gfn, int level,\n \t\t\t\t\t const struct kvm_memory_slot *slot)\n {\n-\tunsigned long idx;\n+\tstruct kvm_rmap_head *rmap_head;\n \n-\tidx = gfn_to_index(gfn, slot-\u003ebase_gfn, level);\n-\treturn \u0026slot-\u003earch.rmap[level - PG_LEVEL_4K][idx];\n+\trmap_head = __idx_to_rmap(slot, level,\n+\t\t\t\t  gfn_to_index(gfn, slot-\u003ebase_gfn, level));\n+\treturn rmap_head ? : \u0026kvm_empty_rmap_head;\n+}\n+\n+static struct kvm_rmap_head *gfn_to_rmap_alloc(struct kvm *kvm,\n+\t\t\t\t\t       struct kvm_mmu_memory_cache *cache,\n+\t\t\t\t\t       gfn_t gfn, int level,\n+\t\t\t\t\t       const struct kvm_memory_slot *slot)\n+{\n+\tunsigned long idx = gfn_to_index(gfn, slot-\u003ebase_gfn, level);\n+\tstruct kvm_rmap_head **chunkp, *chunk;\n+\n+\tlockdep_assert_held_write(\u0026kvm-\u003emmu_lock);\n+\n+\tchunkp = rmap_chunkp(slot, level, idx);\n+\tchunk = *chunkp;\n+\tif (!chunk) {\n+\t\tchunk = kvm_mmu_memory_cache_alloc(cache);\n+\t\t/* Publish the zeroed chunk to lockless walkers. */\n+\t\tsmp_store_release(chunkp, chunk);\n+\t}\n+\n+\treturn \u0026chunk[idx % KVM_RMAP_CHUNK_NR_HEADS];\n }\n \n static void rmap_remove(struct kvm *kvm, u64 *spte)\n@@ -1577,17 +1641,21 @@ struct slot_rmap_walk_iterator {\n \tstruct kvm_rmap_head *rmap;\n \tint level;\n \n-\t/* private field. */\n-\tstruct kvm_rmap_head *end_rmap;\n+\t/* private fields. */\n+\tunsigned long idx;\n+\tunsigned long end_idx;\n };\n \n static void rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator,\n \t\t\t\t int level)\n {\n+\tconst struct kvm_memory_slot *slot = iterator-\u003eslot;\n+\n \titerator-\u003elevel = level;\n \titerator-\u003egfn = iterator-\u003estart_gfn;\n-\titerator-\u003ermap = gfn_to_rmap(iterator-\u003egfn, level, iterator-\u003eslot);\n-\titerator-\u003eend_rmap = gfn_to_rmap(iterator-\u003eend_gfn, level, iterator-\u003eslot);\n+\titerator-\u003eidx = gfn_to_index(iterator-\u003estart_gfn, slot-\u003ebase_gfn, level);\n+\titerator-\u003eend_idx = gfn_to_index(iterator-\u003eend_gfn, slot-\u003ebase_gfn, level);\n+\titerator-\u003ermap = gfn_to_rmap(iterator-\u003egfn, level, slot);\n }\n \n static void slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,\n@@ -1611,11 +1679,27 @@ static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)\n \n static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)\n {\n-\twhile (++iterator-\u003ermap \u003c= iterator-\u003eend_rmap) {\n+\tstruct kvm_rmap_head *rmap_head;\n+\tunsigned long skip;\n+\n+\twhile (++iterator-\u003eidx \u003c= iterator-\u003eend_idx) {\n \t\titerator-\u003egfn += KVM_PAGES_PER_HPAGE(iterator-\u003elevel);\n \n-\t\tif (atomic_long_read(\u0026iterator-\u003ermap-\u003eval))\n+\t\trmap_head = __idx_to_rmap(iterator-\u003eslot, iterator-\u003elevel,\n+\t\t\t\t\t  iterator-\u003eidx);\n+\t\tif (!rmap_head) {\n+\t\t\t/* Skip the rest of the unallocated chunk. */\n+\t\t\tskip = KVM_RMAP_CHUNK_NR_HEADS - 1 -\n+\t\t\t       iterator-\u003eidx % KVM_RMAP_CHUNK_NR_HEADS;\n+\t\t\titerator-\u003eidx += skip;\n+\t\t\titerator-\u003egfn += skip * KVM_PAGES_PER_HPAGE(iterator-\u003elevel);\n+\t\t\tcontinue;\n+\t\t}\n+\n+\t\tif (atomic_long_read(\u0026rmap_head-\u003eval)) {\n+\t\t\titerator-\u003ermap = rmap_head;\n \t\t\treturn;\n+\t\t}\n \t}\n \n \tif (++iterator-\u003elevel \u003e iterator-\u003eend_level) {\n@@ -1734,6 +1818,7 @@ bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)\n \n static void __rmap_add(struct kvm *kvm,\n \t\t       struct kvm_mmu_memory_cache *cache,\n+\t\t       struct kvm_mmu_memory_cache *chunk_cache,\n \t\t       const struct kvm_memory_slot *slot,\n \t\t       u64 *spte, gfn_t gfn, unsigned int access)\n {\n@@ -1745,7 +1830,7 @@ static void __rmap_add(struct kvm *kvm,\n \tkvm_mmu_page_set_translation(sp, spte_index(spte), gfn, access);\n \tkvm_update_page_stats(kvm, sp-\u003erole.level, 1);\n \n-\trmap_head = gfn_to_rmap(gfn, sp-\u003erole.level, slot);\n+\trmap_head = gfn_to_rmap_alloc(kvm, chunk_cache, gfn, sp-\u003erole.level, slot);\n \trmap_count = pte_list_add(kvm, cache, spte, rmap_head);\n \n \tif (rmap_count \u003e kvm-\u003estat.max_mmu_rmap_size)\n@@ -1759,9 +1844,8 @@ static void __rmap_add(struct kvm *kvm,\n static void rmap_add(struct kvm_vcpu *vcpu, const struct kvm_memory_slot *slot,\n \t\t     u64 *spte, gfn_t gfn, unsigned int access)\n {\n-\tstruct kvm_mmu_memory_cache *cache = \u0026vcpu-\u003earch.mmu_pte_list_desc_cache;\n-\n-\t__rmap_add(vcpu-\u003ekvm, cache, slot, spte, gfn, access);\n+\t__rmap_add(vcpu-\u003ekvm, \u0026vcpu-\u003earch.mmu_pte_list_desc_cache,\n+\t\t   \u0026vcpu-\u003earch.mmu_rmap_chunk_cache, slot, spte, gfn, access);\n }\n \n static bool kvm_rmap_age_gfn_range(struct kvm *kvm,\n@@ -6963,6 +7047,8 @@ int kvm_mmu_create(struct kvm_vcpu *vcpu)\n \tvcpu-\u003earch.mmu_pte_list_desc_cache.kmem_cache = pte_list_desc_cache;\n \tvcpu-\u003earch.mmu_pte_list_desc_cache.gfp_zero = __GFP_ZERO;\n \n+\tvcpu-\u003earch.mmu_rmap_chunk_cache.gfp_zero = __GFP_ZERO;\n+\n \tvcpu-\u003earch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;\n \tvcpu-\u003earch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;\n \n@@ -7150,12 +7236,15 @@ int kvm_mmu_init_vm(struct kvm *kvm)\n \n \tkvm-\u003earch.split_desc_cache.kmem_cache = pte_list_desc_cache;\n \tkvm-\u003earch.split_desc_cache.gfp_zero = __GFP_ZERO;\n+\n+\tkvm-\u003earch.split_rmap_chunk_cache.gfp_zero = __GFP_ZERO;\n \treturn 0;\n }\n \n static void mmu_free_vm_memory_caches(struct kvm *kvm)\n {\n \tkvm_mmu_free_memory_cache(\u0026kvm-\u003earch.split_desc_cache);\n+\tkvm_mmu_free_memory_cache(\u0026kvm-\u003earch.split_rmap_chunk_cache);\n \tkvm_mmu_free_memory_cache(\u0026kvm-\u003earch.split_page_header_cache);\n \tkvm_mmu_free_memory_cache(\u0026kvm-\u003earch.split_shadow_page_cache);\n }\n@@ -7274,6 +7363,8 @@ static bool need_topup_split_caches_or_resched(struct kvm *kvm)\n \t * is possible but not worth the complexity.\n \t */\n \treturn need_topup(\u0026kvm-\u003earch.split_desc_cache, SPLIT_DESC_CACHE_MIN_NR_OBJECTS) ||\n+\t       need_topup(\u0026kvm-\u003earch.split_rmap_chunk_cache,\n+\t\t\t  SPLIT_RMAP_CHUNK_CACHE_NR_OBJECTS) ||\n \t       need_topup(\u0026kvm-\u003earch.split_page_header_cache, 1) ||\n \t       need_topup(\u0026kvm-\u003earch.split_shadow_page_cache, 1);\n }\n@@ -7304,6 +7395,12 @@ static int topup_split_caches(struct kvm *kvm)\n \tif (r)\n \t\treturn r;\n \n+\tr = __kvm_mmu_topup_memory_cache(\u0026kvm-\u003earch.split_rmap_chunk_cache,\n+\t\t\t\t\t SPLIT_RMAP_CHUNK_CACHE_NR_OBJECTS,\n+\t\t\t\t\t SPLIT_RMAP_CHUNK_CACHE_NR_OBJECTS);\n+\tif (r)\n+\t\treturn r;\n+\n \tr = kvm_mmu_topup_memory_cache(\u0026kvm-\u003earch.split_page_header_cache, 1);\n \tif (r)\n \t\treturn r;\n@@ -7378,7 +7475,8 @@ static void shadow_mmu_split_huge_page(struct kvm *kvm,\n \n \t\tspte = make_small_spte(kvm, huge_spte, sp-\u003erole, index);\n \t\tmmu_spte_set(sptep, spte);\n-\t\t__rmap_add(kvm, cache, slot, sptep, gfn, sp-\u003erole.access);\n+\t\t__rmap_add(kvm, cache, \u0026kvm-\u003earch.split_rmap_chunk_cache, slot,\n+\t\t\t   sptep, gfn, sp-\u003erole.access);\n \t}\n \n \t__link_shadow_page(kvm, cache, huge_sptep, sp, flush);\ndiff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c\nindex 26e7beaff8a03c..6231c9649c95c6 100644\n--- a/arch/x86/kvm/x86.c\n+++ b/arch/x86/kvm/x86.c\n@@ -10141,12 +10141,27 @@ void kvm_arch_destroy_vm(struct kvm *kvm)\n \tkvm_x86_call(vm_destroy)(kvm);\n }\n \n+static unsigned long memslot_rmap_nr_chunks(struct kvm_memory_slot *slot,\n+\t\t\t\t\t    unsigned long npages, int level)\n+{\n+\treturn DIV_ROUND_UP(__kvm_mmu_slot_lpages(slot, npages, level),\n+\t\t\t    KVM_RMAP_CHUNK_NR_HEADS);\n+}\n+\n static void memslot_rmap_free(struct kvm_memory_slot *slot)\n {\n+\tunsigned long j, nr_chunks;\n \tint i;\n \n \tfor (i = 0; i \u003c KVM_NR_PAGE_SIZES; ++i) {\n-\t\tvfree(slot-\u003earch.rmap[i]);\n+\t\tif (!slot-\u003earch.rmap[i])\n+\t\t\tcontinue;\n+\n+\t\tnr_chunks = memslot_rmap_nr_chunks(slot, slot-\u003enpages, i + 1);\n+\t\tfor (j = 0; j \u003c nr_chunks; j++)\n+\t\t\tfree_page((unsigned long)slot-\u003earch.rmap[i][j]);\n+\n+\t\tkvfree(slot-\u003earch.rmap[i]);\n \t\tslot-\u003earch.rmap[i] = NULL;\n \t}\n }\n@@ -10171,13 +10186,12 @@ int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)\n \tint i;\n \n \tfor (i = 0; i \u003c KVM_NR_PAGE_SIZES; ++i) {\n-\t\tint level = i + 1;\n-\t\tint lpages = __kvm_mmu_slot_lpages(slot, npages, level);\n+\t\tunsigned long nr_chunks = memslot_rmap_nr_chunks(slot, npages, i + 1);\n \n \t\tif (slot-\u003earch.rmap[i])\n \t\t\tcontinue;\n \n-\t\tslot-\u003earch.rmap[i] = __vcalloc(lpages, sz, GFP_KERNEL_ACCOUNT);\n+\t\tslot-\u003earch.rmap[i] = kvcalloc(nr_chunks, sz, GFP_KERNEL_ACCOUNT);\n \t\tif (!slot-\u003earch.rmap[i]) {\n \t\t\tmemslot_rmap_free(slot);\n \t\t\treturn -ENOMEM;\ndiff --git a/tools/testing/selftests/kvm/Makefile.kvm b/tools/testing/selftests/kvm/Makefile.kvm\nindex 17a4256e908191..61d88e0dd0ca8c 100644\n--- a/tools/testing/selftests/kvm/Makefile.kvm\n+++ b/tools/testing/selftests/kvm/Makefile.kvm\n@@ -99,6 +99,7 @@ TEST_GEN_PROGS_x86 += x86/monitor_mwait_test\n TEST_GEN_PROGS_x86 += x86/msrs_test\n TEST_GEN_PROGS_x86 += x86/nested_close_kvm_test\n TEST_GEN_PROGS_x86 += x86/nested_dirty_log_test\n+TEST_GEN_PROGS_x86 += x86/nested_dirty_log_sparse_test\n TEST_GEN_PROGS_x86 += x86/nested_emulation_test\n TEST_GEN_PROGS_x86 += x86/nested_exceptions_test\n TEST_GEN_PROGS_x86 += x86/nested_invalid_cr3_test\ndiff --git a/tools/testing/selftests/kvm/include/x86/processor.h b/tools/testing/selftests/kvm/include/x86/processor.h\nindex 5898a277a2e01c..66293e448ab2b4 100644\n--- a/tools/testing/selftests/kvm/include/x86/processor.h\n+++ b/tools/testing/selftests/kvm/include/x86/processor.h\n@@ -1613,6 +1613,7 @@ void virt_map_level(struct kvm_vm *vm, gva_t gva, gpa_t gpa,\n \n void vm_enable_tdp(struct kvm_vm *vm);\n bool kvm_cpu_has_tdp(void);\n+void __tdp_map(struct kvm_vm *vm, gpa_t l2_gpa, gpa_t gpa, u64 size, int level);\n void tdp_map(struct kvm_vm *vm, gpa_t l2_gpa, gpa_t gpa, u64 size);\n void tdp_identity_map_default_memslots(struct kvm_vm *vm);\n void tdp_identity_map_1g(struct kvm_vm *vm,  u64 addr, u64 size);\ndiff --git a/tools/testing/selftests/kvm/x86/nested_dirty_log_sparse_test.c b/tools/testing/selftests/kvm/x86/nested_dirty_log_sparse_test.c\nnew file mode 100644\nindex 00000000000000..bc1c6b8760c96e\n--- /dev/null\n+++ b/tools/testing/selftests/kvm/x86/nested_dirty_log_sparse_test.c\n@@ -0,0 +1,275 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/*\n+ * Dirty logging of memory that L2 maps sparsely.\n+ *\n+ * KVM allocates shadow MMU rmaps in chunks that cover 2 MiB of guest memory\n+ * at the 4 KiB level, and only for chunks that hold a mapped gfn.  L2 writes\n+ * pages at both ends of a chunk, in the next chunk, and in chunks separated\n+ * by unallocated ones.  Enabling dirty logging write-protects the memslot by\n+ * walking its rmaps, so a mapped page that the walk misses stays writable,\n+ * and L2's next write to it is missing from the dirty log.\n+ *\n+ * A second test maps the memory with 2 MiB pages in L1's TDP page tables and\n+ * verifies that eager page splitting splits the nested huge pages when\n+ * dirty logging is enabled, and that the 4 KiB SPTEs it creates are logged.\n+ */\n+#include \u003cstdio.h\u003e\n+#include \u003cstdlib.h\u003e\n+#include \u003clinux/bitmap.h\u003e\n+#include \u003clinux/bitops.h\u003e\n+#include \u003clinux/sizes.h\u003e\n+\n+#include \"test_util.h\"\n+#include \"kvm_util.h\"\n+#include \"processor.h\"\n+#include \"svm_util.h\"\n+#include \"vmx.h\"\n+\n+#define TEST_MEM_SLOT\t\t1\n+#define TEST_MEM_BASE\t\t0xc0000000ULL\n+\n+/* 64 MiB, i.e. 32 rmap chunks at the 4 KiB level. */\n+#define SPARSE_MEM_PAGES\t(SZ_64M / PAGE_SIZE)\n+\n+/* 4 huge pages for the eager page splitting test. */\n+#define HUGE_MEM_PAGES\t\t(4 * SZ_2M / PAGE_SIZE)\n+#define HUGE_PAGES_PER_2M\t(SZ_2M / PAGE_SIZE)\n+\n+/*\n+ * Page indices L2 writes in the sparse test: both ends of the first two\n+ * chunks, both ends of a chunk surrounded by unallocated chunks, and the\n+ * last page of the memslot.\n+ */\n+static const u64 sparse_pages[] = { 0, 511, 512, 1023, 8192, 8703,\n+\t\t\t\t     SPARSE_MEM_PAGES - 1 };\n+\n+#define NR_SPARSE_PAGES\t\tARRAY_SIZE(sparse_pages)\n+\n+enum test_stage {\n+\tSTAGE_POPULATE = 1,\t/* L2 maps the pages, dirty logging is off */\n+\tSTAGE_ALL,\t\t/* L2 rewrites every page */\n+\tSTAGE_SUBSET,\t\t/* L2 rewrites every other page */\n+};\n+\n+static bool huge_test;\n+\n+static void l2_write(u64 page, u64 val)\n+{\n+\tWRITE_ONCE(*(u64 *)(TEST_MEM_BASE + page * PAGE_SIZE), val);\n+}\n+\n+static u64 nr_test_pages(void)\n+{\n+\treturn huge_test ? HUGE_MEM_PAGES / HUGE_PAGES_PER_2M : NR_SPARSE_PAGES;\n+}\n+\n+/* One page in each huge page in the huge test, the sparse pages otherwise. */\n+static u64 test_page(u64 i)\n+{\n+\treturn huge_test ? i * HUGE_PAGES_PER_2M + 1 : sparse_pages[i];\n+}\n+\n+static void l2_guest_code(void)\n+{\n+\tu64 i;\n+\n+\tfor (i = 0; i \u003c nr_test_pages(); i++)\n+\t\tl2_write(test_page(i), STAGE_POPULATE);\n+\tGUEST_SYNC(STAGE_POPULATE);\n+\n+\tfor (i = 0; i \u003c nr_test_pages(); i++)\n+\t\tl2_write(test_page(i), STAGE_ALL);\n+\tGUEST_SYNC(STAGE_ALL);\n+\n+\tfor (i = 0; i \u003c nr_test_pages(); i += 2)\n+\t\tl2_write(test_page(i), STAGE_SUBSET);\n+\tGUEST_SYNC(STAGE_SUBSET);\n+\n+\tvmcall();\n+}\n+\n+static void l1_vmx_code(struct vmx_pages *vmx)\n+{\n+\tprepare_for_vmx_operation(vmx);\n+\tload_vmcs(vmx);\n+\tprepare_vmcs(vmx, l2_guest_code);\n+\n+\tvmlaunch();\n+\tGUEST_ASSERT_EQ(vmread(VM_EXIT_REASON), EXIT_REASON_VMCALL);\n+\tGUEST_DONE();\n+}\n+\n+static void l1_svm_code(struct svm_test_data *svm)\n+{\n+\tgeneric_svm_setup(svm, l2_guest_code);\n+\n+\trun_guest(svm-\u003evmcb, svm-\u003evmcb_gpa);\n+\tGUEST_ASSERT_EQ(svm-\u003evmcb-\u003econtrol.exit_code, SVM_EXIT_VMMCALL);\n+\tGUEST_DONE();\n+}\n+\n+static void l1_guest_code(void *data)\n+{\n+\tif (this_cpu_has(X86_FEATURE_VMX))\n+\t\tl1_vmx_code(data);\n+\telse\n+\t\tl1_svm_code(data);\n+}\n+\n+/* Returns true if L2 wrote @page in @stage. */\n+static bool page_written(u64 page, enum test_stage stage)\n+{\n+\tu64 i;\n+\n+\tfor (i = 0; i \u003c nr_test_pages(); i++)\n+\t\tif (test_page(i) == page)\n+\t\t\treturn stage != STAGE_SUBSET || !(i % 2);\n+\n+\treturn false;\n+}\n+\n+static void check_dirty_log(struct kvm_vm *vm, u64 npages,\n+\t\t\t    enum test_stage stage, unsigned long *bmap)\n+{\n+\tu64 page;\n+\n+\tkvm_vm_get_dirty_log(vm, TEST_MEM_SLOT, bmap);\n+\n+\tfor (page = 0; page \u003c npages; page++) {\n+\t\tbool written = page_written(page, stage);\n+\n+\t\tTEST_ASSERT(test_bit(page, bmap) == written,\n+\t\t\t    \"Stage %d: page %lu incorrectly reported %s\",\n+\t\t\t    stage, page, written ? \"clean\" : \"dirty\");\n+\t\tif (written)\n+\t\t\tTEST_ASSERT_EQ(*(u64 *)addr_gpa2hva(vm, TEST_MEM_BASE + page * PAGE_SIZE),\n+\t\t\t\t       stage);\n+\t}\n+}\n+\n+static void test_dirty_log(bool nested_tdp, bool huge)\n+{\n+\tu64 npages = huge ? HUGE_MEM_PAGES : SPARSE_MEM_PAGES;\n+\tenum vm_mem_backing_src_type src;\n+\tu64 pages_2m = 0, pages_4k = 0;\n+\tgva_t nested_gva = 0;\n+\tstruct kvm_vcpu *vcpu;\n+\tunsigned long *bmap;\n+\tstruct kvm_vm *vm;\n+\tstruct ucall uc;\n+\n+\tpr_info(\"Nested TDP: %s, L1 TDP page size: %s\\n\",\n+\t\tnested_tdp ? \"enabled\" : \"disabled\", huge ? \"2M\" : \"4K\");\n+\n+\t/* Room for L1's page tables and TDP page tables of the test memory. */\n+\tvm = __vm_create_with_one_vcpu(\u0026vcpu, 2 * (npages / 512 + 16),\n+\t\t\t\t       l1_guest_code);\n+\tif (nested_tdp)\n+\t\tvm_enable_tdp(vm);\n+\n+\tif (kvm_cpu_has(X86_FEATURE_VMX))\n+\t\tvcpu_alloc_vmx(vm, \u0026nested_gva);\n+\telse\n+\t\tvcpu_alloc_svm(vm, \u0026nested_gva);\n+\tvcpu_args_set(vcpu, 1, nested_gva);\n+\n+\tsrc = huge ? VM_MEM_SRC_ANONYMOUS_HUGETLB : VM_MEM_SRC_ANONYMOUS;\n+\tvm_userspace_mem_region_add(vm, src, TEST_MEM_BASE, TEST_MEM_SLOT,\n+\t\t\t\t    npages, 0);\n+\tvirt_map(vm, TEST_MEM_BASE, TEST_MEM_BASE, npages);\n+\n+\tif (nested_tdp) {\n+\t\ttdp_identity_map_default_memslots(vm);\n+\t\t__tdp_map(vm, TEST_MEM_BASE, TEST_MEM_BASE, npages * PAGE_SIZE,\n+\t\t\t  huge ? PG_LEVEL_2M : PG_LEVEL_4K);\n+\t}\n+\n+\thuge_test = huge;\n+\tsync_global_to_guest(vm, huge_test);\n+\n+\tbmap = bitmap_zalloc(npages);\n+\n+\tfor (;;) {\n+\t\tvcpu_run(vcpu);\n+\t\tTEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO);\n+\n+\t\tswitch (get_ucall(vcpu, \u0026uc)) {\n+\t\tcase UCALL_ABORT:\n+\t\t\tREPORT_GUEST_ASSERT(uc);\n+\t\t\t/* NOT REACHED */\n+\t\tcase UCALL_SYNC:\n+\t\t\tbreak;\n+\t\tcase UCALL_DONE:\n+\t\t\tgoto done;\n+\t\tdefault:\n+\t\t\tTEST_FAIL(\"Unknown ucall %lu\", uc.cmd);\n+\t\t}\n+\n+\t\tif (uc.args[1] != STAGE_POPULATE) {\n+\t\t\tcheck_dirty_log(vm, npages, uc.args[1], bmap);\n+\t\t\tcontinue;\n+\t\t}\n+\n+\t\tif (huge) {\n+\t\t\tpages_2m = vm_get_stat(vm, pages_2m);\n+\t\t\tpages_4k = vm_get_stat(vm, pages_4k);\n+\t\t}\n+\n+\t\t/* Write-protect the memslot by walking its rmaps. */\n+\t\tvm_mem_region_set_flags(vm, TEST_MEM_SLOT, KVM_MEM_LOG_DIRTY_PAGES);\n+\n+\t\t/*\n+\t\t * Only L2 maps the test memslot, so eager page splitting must\n+\t\t * have split exactly the nested huge pages L2 populated.\n+\t\t */\n+\t\tif (huge) {\n+\t\t\tu64 nr_huge = npages / HUGE_PAGES_PER_2M;\n+\t\t\tu64 split = pages_2m - vm_get_stat(vm, pages_2m);\n+\n+\t\t\tTEST_ASSERT(split == nr_huge,\n+\t\t\t\t    \"Split %lu nested 2M pages, expected %lu\",\n+\t\t\t\t    split, nr_huge);\n+\t\t\tTEST_ASSERT_EQ(vm_get_stat(vm, pages_4k),\n+\t\t\t\t       pages_4k + nr_huge * HUGE_PAGES_PER_2M);\n+\t\t}\n+\t}\n+\n+done:\n+\tfree(bmap);\n+\tkvm_vm_free(vm);\n+}\n+\n+static u64 free_2m_hugepages(void)\n+{\n+\tu64 nr = 0;\n+\tFILE *f;\n+\n+\tf = fopen(\"/sys/kernel/mm/hugepages/hugepages-2048kB/free_hugepages\", \"r\");\n+\tif (!f)\n+\t\treturn 0;\n+\tif (fscanf(f, \"%lu\", \u0026nr) != 1)\n+\t\tnr = 0;\n+\tfclose(f);\n+\n+\treturn nr;\n+}\n+\n+int main(int argc, char *argv[])\n+{\n+\tTEST_REQUIRE(kvm_cpu_has(X86_FEATURE_VMX) || kvm_cpu_has(X86_FEATURE_SVM));\n+\n+\ttest_dirty_log(/*nested_tdp=*/false, /*huge=*/false);\n+\n+\tif (!kvm_cpu_has_tdp())\n+\t\treturn 0;\n+\n+\ttest_dirty_log(/*nested_tdp=*/true, /*huge=*/false);\n+\n+\tif (free_2m_hugepages() \u003e= HUGE_MEM_PAGES / HUGE_PAGES_PER_2M \u0026\u0026\n+\t    get_kvm_param_bool(\"tdp_mmu\") \u0026\u0026 get_kvm_param_bool(\"eager_page_split\"))\n+\t\ttest_dirty_log(/*nested_tdp=*/true, /*huge=*/true);\n+\telse\n+\t\tpr_info(\"Skipping eager page splitting test, needs 4 free 2M hugepages, tdp_mmu and eager_page_split\\n\");\n+\n+\treturn 0;\n+}\n"
}

2/1 2026/11/06 06:25 agent patch-evaluator
28m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "KVM",
    "KVM_INTEL",
    "KVM_AMD"
  ],
  "FocusSymbols": [
    "memslot_rmap_alloc",
    "memslot_rmap_free",
    "gfn_to_rmap_alloc",
    "slot_rmap_walk_next",
    "shadow_mmu_split_huge_page",
    "kvm_mmu_slot_try_split_huge_pages",
    "kvm_mmu_rmaps_stat_show",
    "kvm_mmu_rmaps_stat_level"
  ],
  "Reasoning": "The patch converts KVM x86 shadow MMU reverse mapping (rmap) arrays into sparse two-level chunk directories allocated on demand. This touches core KVM memory management logic, introducing lockless chunk publication (smp_store_release/READ_ONCE), chunk-skipping iteration in slot_rmap_walk_next, rmap chunk caching during huge page splitting, and new memslot rmap allocation and deallocation paths. This code is fully reachable via KVM ioctls and debugfs, making it a high-value target for 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 5315a724060f567610297263a0938d976c4486c6
Author: syz-cluster <triage@syzkaller.com>
Date:   Fri Nov 6 06:25:41 2026 +0000

    syz-cluster: applied patch under review

diff --git a/arch/x86/include/asm/kvm_host.h b/arch/x86/include/asm/kvm_host.h
index 0378577d9d8bbf..4cc00dc83aba4d 100644
--- a/arch/x86/include/asm/kvm_host.h
+++ b/arch/x86/include/asm/kvm_host.h
@@ -431,6 +431,8 @@ struct kvm_rmap_head {
 	atomic_long_t val;
 };
 
+#define KVM_RMAP_CHUNK_NR_HEADS	(PAGE_SIZE / sizeof(struct kvm_rmap_head))
+
 struct kvm_pio_request {
 	unsigned long count;
 	int in;
@@ -785,6 +787,7 @@ struct kvm_vcpu_arch {
 	u64 pdptrs[4]; /* pae */
 
 	struct kvm_mmu_memory_cache mmu_pte_list_desc_cache;
+	struct kvm_mmu_memory_cache mmu_rmap_chunk_cache;
 	struct kvm_mmu_memory_cache mmu_shadow_page_cache;
 	struct kvm_mmu_memory_cache mmu_shadowed_info_cache;
 	struct kvm_mmu_memory_cache mmu_page_header_cache;
@@ -1044,7 +1047,13 @@ struct kvm_lpage_info {
 };
 
 struct kvm_arch_memory_slot {
-	struct kvm_rmap_head *rmap[KVM_NR_PAGE_SIZES];
+	/*
+	 * Per-level directories of rmap chunks, each chunk holding
+	 * KVM_RMAP_CHUNK_NR_HEADS rmap heads.  Chunks are allocated when KVM
+	 * adds the first SPTE to a head in the chunk's range.  A NULL chunk
+	 * means all of its heads are empty.
+	 */
+	struct kvm_rmap_head **rmap[KVM_NR_PAGE_SIZES];
 	struct kvm_lpage_info *lpage_info[KVM_NR_PAGE_SIZES - 1];
 	unsigned short *gfn_write_track;
 };
@@ -1418,6 +1427,17 @@ struct kvm_arch {
 #define SPLIT_DESC_CACHE_MIN_NR_OBJECTS (SPTE_ENT_PER_PAGE + 1)
 	struct kvm_mmu_memory_cache split_desc_cache;
 
+	/*
+	 * Memory cache used to allocate rmap chunks while splitting huge
+	 * pages.  The rmap heads of the lower level leaf SPTEs of one huge
+	 * page are contiguous, but span two chunks if the memslot's base gfn
+	 * is not aligned to the chunk size.
+	 *
+	 * Protected by kvm->slots_lock.
+	 */
+#define SPLIT_RMAP_CHUNK_CACHE_NR_OBJECTS 2
+	struct kvm_mmu_memory_cache split_rmap_chunk_cache;
+
 	gfn_t gfn_direct_bits;
 	int mirror_root_level;
 
diff --git a/arch/x86/kvm/debugfs.c b/arch/x86/kvm/debugfs.c
index 0074a56e45b44b..0cdb1ef1b18416 100644
--- a/arch/x86/kvm/debugfs.c
+++ b/arch/x86/kvm/debugfs.c
@@ -86,16 +86,43 @@ void kvm_arch_create_vcpu_debugfs(struct kvm_vcpu *vcpu, struct dentry *debugfs_
 
 static const char *kvm_lpage_str[KVM_NR_PAGE_SIZES] = { "4K", "2M", "1G" };
 
+static void kvm_mmu_rmaps_stat_level(struct kvm_memory_slot *slot, int level,
+				     unsigned int *cur)
+{
+	struct kvm_rmap_head **rmap = slot->arch.rmap[level - PG_LEVEL_4K];
+	unsigned long lpages = kvm_mmu_slot_lpages(slot, level);
+	struct kvm_rmap_head *chunk;
+	unsigned long l, nr;
+	unsigned int index;
+
+	for (l = 0; l < lpages; l += nr) {
+		nr = min(lpages - l, KVM_RMAP_CHUNK_NR_HEADS);
+		chunk = rmap[l / KVM_RMAP_CHUNK_NR_HEADS];
+
+		/* An unallocated chunk holds only empty rmaps. */
+		if (!chunk) {
+			cur[0] += nr;
+			continue;
+		}
+
+		for (index = 0; index < nr; index++) {
+			unsigned int bucket = fls(pte_list_count(&chunk[index]));
+
+			if (WARN_ON_ONCE(bucket >= RMAP_LOG_SIZE))
+				bucket = RMAP_LOG_SIZE - 1;
+			cur[bucket]++;
+		}
+	}
+}
+
 static int kvm_mmu_rmaps_stat_show(struct seq_file *m, void *v)
 {
-	struct kvm_rmap_head *rmap;
 	struct kvm *kvm = m->private;
 	struct kvm_memory_slot *slot;
 	struct kvm_memslots *slots;
-	unsigned int lpage_size, index;
 	/* Still small enough to be on the stack */
 	unsigned int *log[KVM_NR_PAGE_SIZES], *cur;
-	int i, j, k, l, ret;
+	int i, j, k, ret;
 
 	if (!kvm_memslots_have_rmaps(kvm))
 		return 0;
@@ -116,17 +143,8 @@ static int kvm_mmu_rmaps_stat_show(struct seq_file *m, void *v)
 
 		slots = __kvm_memslots(kvm, i);
 		kvm_for_each_memslot(slot, bkt, slots)
-			for (k = 0; k < KVM_NR_PAGE_SIZES; k++) {
-				rmap = slot->arch.rmap[k];
-				lpage_size = kvm_mmu_slot_lpages(slot, k + 1);
-				cur = log[k];
-				for (l = 0; l < lpage_size; l++) {
-					index = fls(pte_list_count(&rmap[l]));
-					if (WARN_ON_ONCE(index >= RMAP_LOG_SIZE))
-						index = RMAP_LOG_SIZE - 1;
-					cur[index]++;
-				}
-			}
+			for (k = 0; k < KVM_NR_PAGE_SIZES; k++)
+				kvm_mmu_rmaps_stat_level(slot, k + 1, log[k]);
 	}
 
 	write_unlock(&kvm->mmu_lock);
diff --git a/arch/x86/kvm/mmu/mmu.c b/arch/x86/kvm/mmu/mmu.c
index f4b12d6aef5593..1b958f66764c15 100644
--- a/arch/x86/kvm/mmu/mmu.c
+++ b/arch/x86/kvm/mmu/mmu.c
@@ -612,6 +612,17 @@ static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
 				       1 + PT64_ROOT_MAX_LEVEL + PTE_PREFETCH_NUM);
 	if (r)
 		return r;
+	/*
+	 * 1 rmap chunk for the faulting gfn and 1 per prefetched gfn.  Cap the
+	 * cache at that, as each object is a page.
+	 */
+	if (kvm_memslots_have_rmaps(vcpu->kvm)) {
+		r = __kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_rmap_chunk_cache,
+						 1 + PTE_PREFETCH_NUM,
+						 1 + PTE_PREFETCH_NUM);
+		if (r)
+			return r;
+	}
 	if (kvm_has_mirrored_tdp(vcpu->kvm)) {
 		r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_external_spt_cache,
 					       PT64_ROOT_MAX_LEVEL);
@@ -635,6 +646,7 @@ static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
 {
 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache);
+	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_rmap_chunk_cache);
 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache);
 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadowed_info_cache);
 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_external_spt_cache);
@@ -1236,13 +1248,65 @@ unsigned int pte_list_count(struct kvm_rmap_head *rmap_head)
 	return desc->tail_count + desc->spte_count;
 }
 
+/*
+ * Returned by gfn_to_rmap() for heads in a chunk that hasn't been allocated.
+ * Readers see an empty rmap, and only __rmap_add() writes to a head that may
+ * be empty, after allocating its chunk.
+ */
+static struct kvm_rmap_head kvm_empty_rmap_head;
+
+static struct kvm_rmap_head **
+rmap_chunkp(const struct kvm_memory_slot *slot, int level, unsigned long idx)
+{
+	return &slot->arch.rmap[level - PG_LEVEL_4K][idx / KVM_RMAP_CHUNK_NR_HEADS];
+}
+
+/* Returns NULL if the chunk holding the head hasn't been allocated. */
+static struct kvm_rmap_head *__idx_to_rmap(const struct kvm_memory_slot *slot,
+					   int level, unsigned long idx)
+{
+	struct kvm_rmap_head *chunk;
+
+	/*
+	 * Lockless walkers can observe a chunk being installed.  Pairs with
+	 * the smp_store_release() in gfn_to_rmap_alloc().
+	 */
+	chunk = READ_ONCE(*rmap_chunkp(slot, level, idx));
+	if (!chunk)
+		return NULL;
+
+	return &chunk[idx % KVM_RMAP_CHUNK_NR_HEADS];
+}
+
 static struct kvm_rmap_head *gfn_to_rmap(gfn_t gfn, int level,
 					 const struct kvm_memory_slot *slot)
 {
-	unsigned long idx;
+	struct kvm_rmap_head *rmap_head;
 
-	idx = gfn_to_index(gfn, slot->base_gfn, level);
-	return &slot->arch.rmap[level - PG_LEVEL_4K][idx];
+	rmap_head = __idx_to_rmap(slot, level,
+				  gfn_to_index(gfn, slot->base_gfn, level));
+	return rmap_head ? : &kvm_empty_rmap_head;
+}
+
+static struct kvm_rmap_head *gfn_to_rmap_alloc(struct kvm *kvm,
+					       struct kvm_mmu_memory_cache *cache,
+					       gfn_t gfn, int level,
+					       const struct kvm_memory_slot *slot)
+{
+	unsigned long idx = gfn_to_index(gfn, slot->base_gfn, level);
+	struct kvm_rmap_head **chunkp, *chunk;
+
+	lockdep_assert_held_write(&kvm->mmu_lock);
+
+	chunkp = rmap_chunkp(slot, level, idx);
+	chunk = *chunkp;
+	if (!chunk) {
+		chunk = kvm_mmu_memory_cache_alloc(cache);
+		/* Publish the zeroed chunk to lockless walkers. */
+		smp_store_release(chunkp, chunk);
+	}
+
+	return &chunk[idx % KVM_RMAP_CHUNK_NR_HEADS];
 }
 
 static void rmap_remove(struct kvm *kvm, u64 *spte)
@@ -1577,17 +1641,21 @@ struct slot_rmap_walk_iterator {
 	struct kvm_rmap_head *rmap;
 	int level;
 
-	/* private field. */
-	struct kvm_rmap_head *end_rmap;
+	/* private fields. */
+	unsigned long idx;
+	unsigned long end_idx;
 };
 
 static void rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator,
 				 int level)
 {
+	const struct kvm_memory_slot *slot = iterator->slot;
+
 	iterator->level = level;
 	iterator->gfn = iterator->start_gfn;
-	iterator->rmap = gfn_to_rmap(iterator->gfn, level, iterator->slot);
-	iterator->end_rmap = gfn_to_rmap(iterator->end_gfn, level, iterator->slot);
+	iterator->idx = gfn_to_index(iterator->start_gfn, slot->base_gfn, level);
+	iterator->end_idx = gfn_to_index(iterator->end_gfn, slot->base_gfn, level);
+	iterator->rmap = gfn_to_rmap(iterator->gfn, level, slot);
 }
 
 static void slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
@@ -1611,11 +1679,27 @@ static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
 
 static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
 {
-	while (++iterator->rmap <= iterator->end_rmap) {
+	struct kvm_rmap_head *rmap_head;
+	unsigned long skip;
+
+	while (++iterator->idx <= iterator->end_idx) {
 		iterator->gfn += KVM_PAGES_PER_HPAGE(iterator->level);
 
-		if (atomic_long_read(&iterator->rmap->val))
+		rmap_head = __idx_to_rmap(iterator->slot, iterator->level,
+					  iterator->idx);
+		if (!rmap_head) {
+			/* Skip the rest of the unallocated chunk. */
+			skip = KVM_RMAP_CHUNK_NR_HEADS - 1 -
+			       iterator->idx % KVM_RMAP_CHUNK_NR_HEADS;
+			iterator->idx += skip;
+			iterator->gfn += skip * KVM_PAGES_PER_HPAGE(iterator->level);
+			continue;
+		}
+
+		if (atomic_long_read(&rmap_head->val)) {
+			iterator->rmap = rmap_head;
 			return;
+		}
 	}
 
 	if (++iterator->level > iterator->end_level) {
@@ -1734,6 +1818,7 @@ bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
 
 static void __rmap_add(struct kvm *kvm,
 		       struct kvm_mmu_memory_cache *cache,
+		       struct kvm_mmu_memory_cache *chunk_cache,
 		       const struct kvm_memory_slot *slot,
 		       u64 *spte, gfn_t gfn, unsigned int access)
 {
@@ -1745,7 +1830,7 @@ static void __rmap_add(struct kvm *kvm,
 	kvm_mmu_page_set_translation(sp, spte_index(spte), gfn, access);
 	kvm_update_page_stats(kvm, sp->role.level, 1);
 
-	rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
+	rmap_head = gfn_to_rmap_alloc(kvm, chunk_cache, gfn, sp->role.level, slot);
 	rmap_count = pte_list_add(kvm, cache, spte, rmap_head);
 
 	if (rmap_count > kvm->stat.max_mmu_rmap_size)
@@ -1759,9 +1844,8 @@ static void __rmap_add(struct kvm *kvm,
 static void rmap_add(struct kvm_vcpu *vcpu, const struct kvm_memory_slot *slot,
 		     u64 *spte, gfn_t gfn, unsigned int access)
 {
-	struct kvm_mmu_memory_cache *cache = &vcpu->arch.mmu_pte_list_desc_cache;
-
-	__rmap_add(vcpu->kvm, cache, slot, spte, gfn, access);
+	__rmap_add(vcpu->kvm, &vcpu->arch.mmu_pte_list_desc_cache,
+		   &vcpu->arch.mmu_rmap_chunk_cache, slot, spte, gfn, access);
 }
 
 static bool kvm_rmap_age_gfn_range(struct kvm *kvm,
@@ -6963,6 +7047,8 @@ int kvm_mmu_create(struct kvm_vcpu *vcpu)
 	vcpu->arch.mmu_pte_list_desc_cache.kmem_cache = pte_list_desc_cache;
 	vcpu->arch.mmu_pte_list_desc_cache.gfp_zero = __GFP_ZERO;
 
+	vcpu->arch.mmu_rmap_chunk_cache.gfp_zero = __GFP_ZERO;
+
 	vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
 	vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
 
@@ -7150,12 +7236,15 @@ int kvm_mmu_init_vm(struct kvm *kvm)
 
 	kvm->arch.split_desc_cache.kmem_cache = pte_list_desc_cache;
 	kvm->arch.split_desc_cache.gfp_zero = __GFP_ZERO;
+
+	kvm->arch.split_rmap_chunk_cache.gfp_zero = __GFP_ZERO;
 	return 0;
 }
 
 static void mmu_free_vm_memory_caches(struct kvm *kvm)
 {
 	kvm_mmu_free_memory_cache(&kvm->arch.split_desc_cache);
+	kvm_mmu_free_memory_cache(&kvm->arch.split_rmap_chunk_cache);
 	kvm_mmu_free_memory_cache(&kvm->arch.split_page_header_cache);
 	kvm_mmu_free_memory_cache(&kvm->arch.split_shadow_page_cache);
 }
@@ -7274,6 +7363,8 @@ static bool need_topup_split_caches_or_resched(struct kvm *kvm)
 	 * is possible but not worth the complexity.
 	 */
 	return need_topup(&kvm->arch.split_desc_cache, SPLIT_DESC_CACHE_MIN_NR_OBJECTS) ||
+	       need_topup(&kvm->arch.split_rmap_chunk_cache,
+			  SPLIT_RMAP_CHUNK_CACHE_NR_OBJECTS) ||
 	       need_topup(&kvm->arch.split_page_header_cache, 1) ||
 	       need_topup(&kvm->arch.split_shadow_page_cache, 1);
 }
@@ -7304,6 +7395,12 @@ static int topup_split_caches(struct kvm *kvm)
 	if (r)
 		return r;
 
+	r = __kvm_mmu_topup_memory_cache(&kvm->arch.split_rmap_chunk_cache,
+					 SPLIT_RMAP_CHUNK_CACHE_NR_OBJECTS,
+					 SPLIT_RMAP_CHUNK_CACHE_NR_OBJECTS);
+	if (r)
+		return r;
+
 	r = kvm_mmu_topup_memory_cache(&kvm->arch.split_page_header_cache, 1);
 	if (r)
 		return r;
@@ -7378,7 +7475,8 @@ static void shadow_mmu_split_huge_page(struct kvm *kvm,
 
 		spte = make_small_spte(kvm, huge_spte, sp->role, index);
 		mmu_spte_set(sptep, spte);
-		__rmap_add(kvm, cache, slot, sptep, gfn, sp->role.access);
+		__rmap_add(kvm, cache, &kvm->arch.split_rmap_chunk_cache, slot,
+			   sptep, gfn, sp->role.access);
 	}
 
 	__link_shadow_page(kvm, cache, huge_sptep, sp, flush);
diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c
index 26e7beaff8a03c..6231c9649c95c6 100644
--- a/arch/x86/kvm/x86.c
+++ b/arch/x86/kvm/x86.c
@@ -10141,12 +10141,27 @@ void kvm_arch_destroy_vm(struct kvm *kvm)
 	kvm_x86_call(vm_destroy)(kvm);
 }
 
+static unsigned long memslot_rmap_nr_chunks(struct kvm_memory_slot *slot,
+					    unsigned long npages, int level)
+{
+	return DIV_ROUND_UP(__kvm_mmu_slot_lpages(slot, npages, level),
+			    KVM_RMAP_CHUNK_NR_HEADS);
+}
+
 static void memslot_rmap_free(struct kvm_memory_slot *slot)
 {
+	unsigned long j, nr_chunks;
 	int i;
 
 	for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
-		vfree(slot->arch.rmap[i]);
+		if (!slot->arch.rmap[i])
+			continue;
+
+		nr_chunks = memslot_rmap_nr_chunks(slot, slot->npages, i + 1);
+		for (j = 0; j < nr_chunks; j++)
+			free_page((unsigned long)slot->arch.rmap[i][j]);
+
+		kvfree(slot->arch.rmap[i]);
 		slot->arch.rmap[i] = NULL;
 	}
 }
@@ -10171,13 +10186,12 @@ int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)
 	int i;
 
 	for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
-		int level = i + 1;
-		int lpages = __kvm_mmu_slot_lpages(slot, npages, level);
+		unsigned long nr_chunks = memslot_rmap_nr_chunks(slot, npages, i + 1);
 
 		if (slot->arch.rmap[i])
 			continue;
 
-		slot->arch.rmap[i] = __vcalloc(lpages, sz, GFP_KERNEL_ACCOUNT);
+		slot->arch.rmap[i] = kvcalloc(nr_chunks, sz, GFP_KERNEL_ACCOUNT);
 		if (!slot->arch.rmap[i]) {
 			memslot_rmap_free(slot);
 			return -ENOMEM;
diff --git a/tools/testing/selftests/kvm/Makefile.kvm b/tools/testing/selftests/kvm/Makefile.kvm
index 17a4256e908191..61d88e0dd0ca8c 100644
--- a/tools/testing/selftests/kvm/Makefile.kvm
+++ b/tools/testing/selftests/kvm/Makefile.kvm
@@ -99,6 +99,7 @@ TEST_GEN_PROGS_x86 += x86/monitor_mwait_test
 TEST_GEN_PROGS_x86 += x86/msrs_test
 TEST_GEN_PROGS_x86 += x86/nested_close_kvm_test
 TEST_GEN_PROGS_x86 += x86/nested_dirty_log_test
+TEST_GEN_PROGS_x86 += x86/nested_dirty_log_sparse_test
 TEST_GEN_PROGS_x86 += x86/nested_emulation_test
 TEST_GEN_PROGS_x86 += x86/nested_exceptions_test
 TEST_GEN_PROGS_x86 += x86/nested_invalid_cr3_test
diff --git a/tools/testing/selftests/kvm/include/x86/processor.h b/tools/testing/selftests/kvm/include/x86/processor.h
index 5898a277a2e01c..66293e448ab2b4 100644
--- a/tools/testing/selftests/kvm/include/x86/processor.h
+++ b/tools/testing/selftests/kvm/include/x86/processor.h
@@ -1613,6 +1613,7 @@ void virt_map_level(struct kvm_vm *vm, gva_t gva, gpa_t gpa,
 
 void vm_enable_tdp(struct kvm_vm *vm);
 bool kvm_cpu_has_tdp(void);
+void __tdp_map(struct kvm_vm *vm, gpa_t l2_gpa, gpa_t gpa, u64 size, int level);
 void tdp_map(struct kvm_vm *vm, gpa_t l2_gpa, gpa_t gpa, u64 size);
 void tdp_identity_map_default_memslots(struct kvm_vm *vm);
 void tdp_identity_map_1g(struct kvm_vm *vm,  u64 addr, u64 size);
diff --git a/tools/testing/selftests/kvm/x86/nested_dirty_log_sparse_test.c b/tools/testing/selftests/kvm/x86/nested_dirty_log_sparse_test.c
new file mode 100644
index 00000000000000..bc1c6b8760c96e
--- /dev/null
+++ b/tools/testing/selftests/kvm/x86/nested_dirty_log_sparse_test.c
@@ -0,0 +1,275 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Dirty logging of memory that L2 maps sparsely.
+ *
+ * KVM allocates shadow MMU rmaps in chunks that cover 2 MiB of guest memory
+ * at the 4 KiB level, and only for chunks that hold a mapped gfn.  L2 writes
+ * pages at both ends of a chunk, in the next chunk, and in chunks separated
+ * by unallocated ones.  Enabling dirty logging write-protects the memslot by
+ * walking its rmaps, so a mapped page that the walk misses stays writable,
+ * and L2's next write to it is missing from the dirty log.
+ *
+ * A second test maps the memory with 2 MiB pages in L1's TDP page tables and
+ * verifies that eager page splitting splits the nested huge pages when
+ * dirty logging is enabled, and that the 4 KiB SPTEs it creates are logged.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <linux/bitmap.h>
+#include <linux/bitops.h>
+#include <linux/sizes.h>
+
+#include "test_util.h"
+#include "kvm_util.h"
+#include "processor.h"
+#include "svm_util.h"
+#include "vmx.h"
+
+#define TEST_MEM_SLOT		1
+#define TEST_MEM_BASE		0xc0000000ULL
+
+/* 64 MiB, i.e. 32 rmap chunks at the 4 KiB level. */
+#define SPARSE_MEM_PAGES	(SZ_64M / PAGE_SIZE)
+
+/* 4 huge pages for the eager page splitting test. */
+#define HUGE_MEM_PAGES		(4 * SZ_2M / PAGE_SIZE)
+#define HUGE_PAGES_PER_2M	(SZ_2M / PAGE_SIZE)
+
+/*
+ * Page indices L2 writes in the sparse test: both ends of the first two
+ * chunks, both ends of a chunk surrounded by unallocated chunks, and the
+ * last page of the memslot.
+ */
+static const u64 sparse_pages[] = { 0, 511, 512, 1023, 8192, 8703,
+				     SPARSE_MEM_PAGES - 1 };
+
+#define NR_SPARSE_PAGES		ARRAY_SIZE(sparse_pages)
+
+enum test_stage {
+	STAGE_POPULATE = 1,	/* L2 maps the pages, dirty logging is off */
+	STAGE_ALL,		/* L2 rewrites every page */
+	STAGE_SUBSET,		/* L2 rewrites every other page */
+};
+
+static bool huge_test;
+
+static void l2_write(u64 page, u64 val)
+{
+	WRITE_ONCE(*(u64 *)(TEST_MEM_BASE + page * PAGE_SIZE), val);
+}
+
+static u64 nr_test_pages(void)
+{
+	return huge_test ? HUGE_MEM_PAGES / HUGE_PAGES_PER_2M : NR_SPARSE_PAGES;
+}
+
+/* One page in each huge page in the huge test, the sparse pages otherwise. */
+static u64 test_page(u64 i)
+{
+	return huge_test ? i * HUGE_PAGES_PER_2M + 1 : sparse_pages[i];
+}
+
+static void l2_guest_code(void)
+{
+	u64 i;
+
+	for (i = 0; i < nr_test_pages(); i++)
+		l2_write(test_page(i), STAGE_POPULATE);
+	GUEST_SYNC(STAGE_POPULATE);
+
+	for (i = 0; i < nr_test_pages(); i++)
+		l2_write(test_page(i), STAGE_ALL);
+	GUEST_SYNC(STAGE_ALL);
+
+	for (i = 0; i < nr_test_pages(); i += 2)
+		l2_write(test_page(i), STAGE_SUBSET);
+	GUEST_SYNC(STAGE_SUBSET);
+
+	vmcall();
+}
+
+static void l1_vmx_code(struct vmx_pages *vmx)
+{
+	prepare_for_vmx_operation(vmx);
+	load_vmcs(vmx);
+	prepare_vmcs(vmx, l2_guest_code);
+
+	vmlaunch();
+	GUEST_ASSERT_EQ(vmread(VM_EXIT_REASON), EXIT_REASON_VMCALL);
+	GUEST_DONE();
+}
+
+static void l1_svm_code(struct svm_test_data *svm)
+{
+	generic_svm_setup(svm, l2_guest_code);
+
+	run_guest(svm->vmcb, svm->vmcb_gpa);
+	GUEST_ASSERT_EQ(svm->vmcb->control.exit_code, SVM_EXIT_VMMCALL);
+	GUEST_DONE();
+}
+
+static void l1_guest_code(void *data)
+{
+	if (this_cpu_has(X86_FEATURE_VMX))
+		l1_vmx_code(data);
+	else
+		l1_svm_code(data);
+}
+
+/* Returns true if L2 wrote @page in @stage. */
+static bool page_written(u64 page, enum test_stage stage)
+{
+	u64 i;
+
+	for (i = 0; i < nr_test_pages(); i++)
+		if (test_page(i) == page)
+			return stage != STAGE_SUBSET || !(i % 2);
+
+	return false;
+}
+
+static void check_dirty_log(struct kvm_vm *vm, u64 npages,
+			    enum test_stage stage, unsigned long *bmap)
+{
+	u64 page;
+
+	kvm_vm_get_dirty_log(vm, TEST_MEM_SLOT, bmap);
+
+	for (page = 0; page < npages; page++) {
+		bool written = page_written(page, stage);
+
+		TEST_ASSERT(test_bit(page, bmap) == written,
+			    "Stage %d: page %lu incorrectly reported %s",
+			    stage, page, written ? "clean" : "dirty");
+		if (written)
+			TEST_ASSERT_EQ(*(u64 *)addr_gpa2hva(vm, TEST_MEM_BASE + page * PAGE_SIZE),
+				       stage);
+	}
+}
+
+static void test_dirty_log(bool nested_tdp, bool huge)
+{
+	u64 npages = huge ? HUGE_MEM_PAGES : SPARSE_MEM_PAGES;
+	enum vm_mem_backing_src_type src;
+	u64 pages_2m = 0, pages_4k = 0;
+	gva_t nested_gva = 0;
+	struct kvm_vcpu *vcpu;
+	unsigned long *bmap;
+	struct kvm_vm *vm;
+	struct ucall uc;
+
+	pr_info("Nested TDP: %s, L1 TDP page size: %s\n",
+		nested_tdp ? "enabled" : "disabled", huge ? "2M" : "4K");
+
+	/* Room for L1's page tables and TDP page tables of the test memory. */
+	vm = __vm_create_with_one_vcpu(&vcpu, 2 * (npages / 512 + 16),
+				       l1_guest_code);
+	if (nested_tdp)
+		vm_enable_tdp(vm);
+
+	if (kvm_cpu_has(X86_FEATURE_VMX))
+		vcpu_alloc_vmx(vm, &nested_gva);
+	else
+		vcpu_alloc_svm(vm, &nested_gva);
+	vcpu_args_set(vcpu, 1, nested_gva);
+
+	src = huge ? VM_MEM_SRC_ANONYMOUS_HUGETLB : VM_MEM_SRC_ANONYMOUS;
+	vm_userspace_mem_region_add(vm, src, TEST_MEM_BASE, TEST_MEM_SLOT,
+				    npages, 0);
+	virt_map(vm, TEST_MEM_BASE, TEST_MEM_BASE, npages);
+
+	if (nested_tdp) {
+		tdp_identity_map_default_memslots(vm);
+		__tdp_map(vm, TEST_MEM_BASE, TEST_MEM_BASE, npages * PAGE_SIZE,
+			  huge ? PG_LEVEL_2M : PG_LEVEL_4K);
+	}
+
+	huge_test = huge;
+	sync_global_to_guest(vm, huge_test);
+
+	bmap = bitmap_zalloc(npages);
+
+	for (;;) {
+		vcpu_run(vcpu);
+		TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO);
+
+		switch (get_ucall(vcpu, &uc)) {
+		case UCALL_ABORT:
+			REPORT_GUEST_ASSERT(uc);
+			/* NOT REACHED */
+		case UCALL_SYNC:
+			break;
+		case UCALL_DONE:
+			goto done;
+		default:
+			TEST_FAIL("Unknown ucall %lu", uc.cmd);
+		}
+
+		if (uc.args[1] != STAGE_POPULATE) {
+			check_dirty_log(vm, npages, uc.args[1], bmap);
+			continue;
+		}
+
+		if (huge) {
+			pages_2m = vm_get_stat(vm, pages_2m);
+			pages_4k = vm_get_stat(vm, pages_4k);
+		}
+
+		/* Write-protect the memslot by walking its rmaps. */
+		vm_mem_region_set_flags(vm, TEST_MEM_SLOT, KVM_MEM_LOG_DIRTY_PAGES);
+
+		/*
+		 * Only L2 maps the test memslot, so eager page splitting must
+		 * have split exactly the nested huge pages L2 populated.
+		 */
+		if (huge) {
+			u64 nr_huge = npages / HUGE_PAGES_PER_2M;
+			u64 split = pages_2m - vm_get_stat(vm, pages_2m);
+
+			TEST_ASSERT(split == nr_huge,
+				    "Split %lu nested 2M pages, expected %lu",
+				    split, nr_huge);
+			TEST_ASSERT_EQ(vm_get_stat(vm, pages_4k),
+				       pages_4k + nr_huge * HUGE_PAGES_PER_2M);
+		}
+	}
+
+done:
+	free(bmap);
+	kvm_vm_free(vm);
+}
+
+static u64 free_2m_hugepages(void)
+{
+	u64 nr = 0;
+	FILE *f;
+
+	f = fopen("/sys/kernel/mm/hugepages/hugepages-2048kB/free_hugepages", "r");
+	if (!f)
+		return 0;
+	if (fscanf(f, "%lu", &nr) != 1)
+		nr = 0;
+	fclose(f);
+
+	return nr;
+}
+
+int main(int argc, char *argv[])
+{
+	TEST_REQUIRE(kvm_cpu_has(X86_FEATURE_VMX) || kvm_cpu_has(X86_FEATURE_SVM));
+
+	test_dirty_log(/*nested_tdp=*/false, /*huge=*/false);
+
+	if (!kvm_cpu_has_tdp())
+		return 0;
+
+	test_dirty_log(/*nested_tdp=*/true, /*huge=*/false);
+
+	if (free_2m_hugepages() >= HUGE_MEM_PAGES / HUGE_PAGES_PER_2M &&
+	    get_kvm_param_bool("tdp_mmu") && get_kvm_param_bool("eager_page_split"))
+		test_dirty_log(/*nested_tdp=*/true, /*huge=*/true);
+	else
+		pr_info("Skipping eager page splitting test, needs 4 free 2M hugepages, tdp_mmu and eager_page_split\n");
+
+	return 0;
+}

3/2 2026/11/06 06:25 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 13158
							output: 25
							thoughts: 1323
						

Thoughts:
**Analyzing a KVM x86 MMU Optimization Patch**

Okay, let's dive into this patch. I see it's touching KVM for x86, specifically around the MMU. The files changed are a good indicator: `kvm_host.h`, `debugfs.c`, `mmu/mmu.c`, `x86.c`, and some selftests.

My initial thought is to understand *why* this change is happening. I need to get the context – what problem is it solving, and what's the rationale? Time to look at the commit log. I'll need to use `grepper`, `read-file` and `codesearch-dir-index`, as I don't have direct access to `git log`.

Right, let's examine the actual code. It looks like `arch/x86/include/asm/kvm_host.h` now defines `KVM_RMAP_CHUNK_NR_HEADS` and introduces `struct kvm_mmu_memory_cache`. In `struct kvm_arch_memory_slot`, the `rmap` array has been changed from a flat array of `struct kvm_rmap_head` to an array of pointers to `struct kvm_rmap_head` (`struct kvm_rmap_head **rmap`). And there's also `struct kvm_mmu_memory_cache split_rmap_chunk_cache`.

Okay, I'm starting to get it. This indicates a move towards sparse rmap allocation. Instead of pre-allocating the entire rmap table for each memory slot for each page size, chunks of rmap heads are now allocated on demand. A NULL chunk signals that the heads within it are empty. The debugfs changes indicate that it's handling this NULL chunk scenario.

The `mmu.c` modifications support this sparse approach. There are functions to manage and top up memory caches (`mmu_rmap_chunk_cache`, `split_rmap_chunk_cache`). Functions dealing with rmap head access like `gfn_to_rmap`, allocation (`gfn_to_rmap_alloc`), initialization (`kvm_mmu_create`, `kvm_mmu_init_vm`), and the splitting of huge pages all seem to be updated to use this new chunk-based system. `x86.c` contains functions like `memslot_rmap_alloc` that allocates the array of pointers using `kvcalloc`, instead of allocating the entire rmap table upfront.

This is a significant optimization! Allocating rmap chunks only when needed should save a lot of memory, especially in VMs with large address spaces.

Now, the question is: is this reachable? Is this worth fuzzing?

I need to apply the fuzzing triage philosophy I use. Reachability is the primary gate. Can this code be executed in a standard virtualized environment like GCE or QEMU, preferably with software-emulated devices? Ah, but does KVM *itself* run in those environments? And what about nested virtualization?

Wait... I remember Syzkaller. Does Syzkaller fuzz /dev/kvm? Yes! I know Syzkaller heavily fuzzes KVM. So, /dev/kvm is definitely a target. That's good!

But, does the shadow MMU and the rmaps in question function in QEMU, in nested virt or with TDP disabled/nested KVM? I need to figure out when these rmaps are actually used.

I'll check `kvm_memslots_have_rmaps`. Time to `grepper` that and get some context.



4/2 2026/11/06 06:27 tool grepper
0m Args:
{
  "Expression": "kvm_memslots_have_rmaps"
}

Results:
{
  "Output": "arch/x86/kvm/debugfs.c=118=static int kvm_mmu_rmaps_stat_show(struct seq_file *m, void *v)\n--\narch/x86/kvm/debugfs.c-126-\narch/x86/kvm/debugfs.c:127:\tif (!kvm_memslots_have_rmaps(kvm))\narch/x86/kvm/debugfs.c-128-\t\treturn 0;\n--\narch/x86/kvm/mmu.h=342=int kvm_tdp_mmu_map_private_pfn(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn);\narch/x86/kvm/mmu.h-343-\narch/x86/kvm/mmu.h:344:static inline bool kvm_memslots_have_rmaps(struct kvm *kvm)\narch/x86/kvm/mmu.h-345-{\n--\narch/x86/kvm/mmu/mmu.c=606=static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)\n--\narch/x86/kvm/mmu/mmu.c-618-\t */\narch/x86/kvm/mmu/mmu.c:619:\tif (kvm_memslots_have_rmaps(vcpu-\u003ekvm)) {\narch/x86/kvm/mmu/mmu.c-620-\t\tr = __kvm_mmu_topup_memory_cache(\u0026vcpu-\u003earch.mmu_rmap_chunk_cache,\n--\narch/x86/kvm/mmu/mmu.c=1497=static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-1506-\narch/x86/kvm/mmu/mmu.c:1507:\tif (!kvm_memslots_have_rmaps(kvm))\narch/x86/kvm/mmu/mmu.c-1508-\t\treturn;\n--\narch/x86/kvm/mmu/mmu.c=1520=static void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-1529-\narch/x86/kvm/mmu/mmu.c:1530:\tif (!kvm_memslots_have_rmaps(kvm))\narch/x86/kvm/mmu/mmu.c-1531-\t\treturn;\n--\narch/x86/kvm/mmu/mmu.c=1595=bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-1602-\narch/x86/kvm/mmu/mmu.c:1603:\tif (kvm_memslots_have_rmaps(kvm)) {\narch/x86/kvm/mmu/mmu.c-1604-\t\tfor (i = min_level; i \u003c= KVM_MAX_HUGEPAGE_LEVEL; ++i) {\n--\narch/x86/kvm/mmu/mmu.c=1787=bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)\n--\narch/x86/kvm/mmu/mmu.c-1801-\narch/x86/kvm/mmu/mmu.c:1802:\tif (kvm_memslots_have_rmaps(kvm))\narch/x86/kvm/mmu/mmu.c-1803-\t\tflush = __kvm_rmap_zap_gfn_range(kvm, range-\u003eslot,\n--\narch/x86/kvm/mmu/mmu.c=4208=static int mmu_first_shadow_root_alloc(struct kvm *kvm)\n--\narch/x86/kvm/mmu/mmu.c-4234-\t */\narch/x86/kvm/mmu/mmu.c:4235:\tif (kvm_memslots_have_rmaps(kvm) \u0026\u0026\narch/x86/kvm/mmu/mmu.c-4236-\t    kvm_page_track_write_tracking_enabled(kvm))\n--\narch/x86/kvm/mmu/mmu.c=7262=static bool kvm_rmap_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)\n--\narch/x86/kvm/mmu/mmu.c-7270-\narch/x86/kvm/mmu/mmu.c:7271:\tif (!kvm_memslots_have_rmaps(kvm))\narch/x86/kvm/mmu/mmu.c-7272-\t\treturn flush;\n--\narch/x86/kvm/mmu/mmu.c=7332=void kvm_mmu_slot_remove_write_access(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-7335-{\narch/x86/kvm/mmu/mmu.c:7336:\tif (kvm_memslots_have_rmaps(kvm)) {\narch/x86/kvm/mmu/mmu.c-7337-\t\twrite_lock(\u0026kvm-\u003emmu_lock);\n--\narch/x86/kvm/mmu/mmu.c=7589=void kvm_mmu_try_split_huge_pages(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-7596-\narch/x86/kvm/mmu/mmu.c:7597:\tif (kvm_memslots_have_rmaps(kvm))\narch/x86/kvm/mmu/mmu.c-7598-\t\tkvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);\n--\narch/x86/kvm/mmu/mmu.c=7608=void kvm_mmu_slot_try_split_huge_pages(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-7617-\narch/x86/kvm/mmu/mmu.c:7618:\tif (kvm_memslots_have_rmaps(kvm)) {\narch/x86/kvm/mmu/mmu.c-7619-\t\twrite_lock(\u0026kvm-\u003emmu_lock);\n--\narch/x86/kvm/mmu/mmu.c=7693=void kvm_mmu_recover_huge_pages(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-7695-{\narch/x86/kvm/mmu/mmu.c:7696:\tif (kvm_memslots_have_rmaps(kvm)) {\narch/x86/kvm/mmu/mmu.c-7697-\t\twrite_lock(\u0026kvm-\u003emmu_lock);\n--\narch/x86/kvm/mmu/mmu.c=7709=void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-7711-{\narch/x86/kvm/mmu/mmu.c:7712:\tif (kvm_memslots_have_rmaps(kvm)) {\narch/x86/kvm/mmu/mmu.c-7713-\t\twrite_lock(\u0026kvm-\u003emmu_lock);\n--\narch/x86/kvm/x86.c=10204=static int kvm_alloc_memslot_metadata(struct kvm *kvm,\n--\narch/x86/kvm/x86.c-10216-\narch/x86/kvm/x86.c:10217:\tif (kvm_memslots_have_rmaps(kvm)) {\narch/x86/kvm/x86.c-10218-\t\tr = memslot_rmap_alloc(slot, npages);\n"
}

5/2 2026/11/06 06:27 llm patch-evaluator
10m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 17583
							output: 41
							thoughts: 49
						

Thoughts:
Okay, let's dive into this. Here's how I'd approach this task:

**Deconstructing `kvm_memslots_have_rmaps`**

My first instinct is to understand the definition of `kvm_memslots_have_rmaps`. I need to figure out what this macro or function represents. My go-to approach is to check the relevant header files. Given the context, it's highly likely that this is defined within the KVM infrastructure, specifically related to memory management. So, I need to consult `arch/x86/kvm/mmu.h`. Knowing the general structure of the KVM codebase, and likely that this is a relatively core function, I'd start around line 344 in `arch/x86/kvm/mmu.h`. I expect to find the actual definition or macro expansion there, which will hopefully illuminate its purpose and behavior. From there I can start putting the pieces together.



6/2 2026/11/06 06:37 tool read-file
0m Args:
{
  "File": "arch/x86/kvm/mmu.h",
  "FirstLine": 340,
  "LineCount": 20
}

Results:
{
  "Contents": " 340:\t}\n 341:\t\n 342:\tint kvm_tdp_mmu_map_private_pfn(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn);\n 343:\t\n 344:\tstatic inline bool kvm_memslots_have_rmaps(struct kvm *kvm)\n 345:\t{\n 346:\t\treturn !tdp_mmu_enabled || kvm_shadow_root_allocated(kvm);\n 347:\t}\n 348:\t\n 349:\tstatic inline gfn_t gfn_to_index(gfn_t gfn, gfn_t base_gfn, int level)\n 350:\t{\n 351:\t\t/* KVM_HPAGE_GFN_SHIFT(PG_LEVEL_4K) must be 0. */\n 352:\t\treturn (gfn \u003e\u003e KVM_HPAGE_GFN_SHIFT(level)) -\n 353:\t\t\t(base_gfn \u003e\u003e KVM_HPAGE_GFN_SHIFT(level));\n 354:\t}\n 355:\t\n 356:\tstatic inline unsigned long\n 357:\t__kvm_mmu_slot_lpages(struct kvm_memory_slot *slot, unsigned long npages,\n 358:\t\t\t      int level)\n 359:\t{\n"
}

7/2 2026/11/06 06:37 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 18258
							output: 34
							thoughts: 2427
						

Thoughts:
**KVM Rmap Structure Refactoring: A Deep Dive**

Okay, so I've been looking at this patch and, yeah, it's definitely going to be interesting to fuzz. First, let's establish the context: `kvm_memslots_have_rmaps` is crucial here, and the changes revolve around how the rmap structures in KVM are handled. Essentially, the patch is swapping out a contiguous, flat array of `struct kvm_rmap_head` for an array of pointers to these structures, chunked at `KVM_RMAP_CHUNK_NR_HEADS` which are allocated on demand using a cache. It's a fundamental shift in memory management within KVM's MMU.

Now, KVM is absolutely reachable through Syzkaller. We've got the usual suspects – `KVM_SET_USER_MEMORY_REGION`, `KVM_RUN`, and the rest. Dirty logging, nested virtualization (which QEMU can do, right with `-cpu host` or nested virt), page/write tracking, and all the ioctls are entry points. The fact that standard QEMU can run nested KVM or even use shadow paging means this is an active target. And the rules for "WorthFuzzing" are clearly met here, as we are dealing with core logic modifications.

Diving into the patch itself, the shift from flat arrays to chunked pointers is a big deal. We're talking about a two-level structure now, with on-demand allocation and a cache to help. The critical thing to note is the use of `READ_ONCE` and `smp_store_release` for lockless walkers, which means there's a concurrency aspect here that's new and needs to be evaluated. Plus, there are some pretty complex index calculations to skip chunks. And then, there are memory caching changes, and more locking and memory management.

The change to using the chunks, and then the need to skip chunks during iteration. The lockdep assertion and the warning make the change even more interesting. This is not just a cosmetic change, this is a significant restructuring of how memory is managed in KVM's MMU.

Considering the "FocusSymbols" criteria, we need to pick key functions that implement this new logic. Looking at the files, in `arch/x86/kvm/mmu/mmu.c`, we've got a lot of changes in the memory management which are new: `gfn_to_rmap_alloc`, `__rmap_add`, `rmap_add`, `slot_rmap_walk_next`, and others. Then in `arch/x86/kvm/x86.c`, we have `memslot_rmap_alloc`, `memslot_rmap_free` and `memslot_rmap_nr_chunks`. Also in `arch/x86/kvm/debugfs.c`, we have `kvm_mmu_rmaps_stat_level` and a modification to `kvm_mmu_rmaps_stat_show`.

I also have to see if these symbols are static, as static functions aren't directly targetable and we'd need to consider their callers. I'll need to figure out which of these are not inlined by the compiler. We can search for callers of functions to help guide us. `rmap_add` or `slot_rmap_walk_next` are good starting points.



8/2 2026/11/06 06:39 tool grepper
0m Args:
{
  "Expression": "rmap_add\\(",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/mmu/mmu.c=1237=unsigned int pte_list_count(struct kvm_rmap_head *rmap_head)\n--\narch/x86/kvm/mmu/mmu.c-1252- * Returned by gfn_to_rmap() for heads in a chunk that hasn't been allocated.\narch/x86/kvm/mmu/mmu.c:1253: * Readers see an empty rmap, and only __rmap_add() writes to a head that may\narch/x86/kvm/mmu/mmu.c-1254- * be empty, after allocating its chunk.\n--\narch/x86/kvm/mmu/mmu.c=1787=bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)\n--\narch/x86/kvm/mmu/mmu.c-1818-\narch/x86/kvm/mmu/mmu.c:1819:static void __rmap_add(struct kvm *kvm,\narch/x86/kvm/mmu/mmu.c-1820-\t\t       struct kvm_mmu_memory_cache *cache,\n--\narch/x86/kvm/mmu/mmu.c-1843-\narch/x86/kvm/mmu/mmu.c:1844:static void rmap_add(struct kvm_vcpu *vcpu, const struct kvm_memory_slot *slot,\narch/x86/kvm/mmu/mmu.c-1845-\t\t     u64 *spte, gfn_t gfn, unsigned int access)\narch/x86/kvm/mmu/mmu.c-1846-{\narch/x86/kvm/mmu/mmu.c:1847:\t__rmap_add(vcpu-\u003ekvm, \u0026vcpu-\u003earch.mmu_pte_list_desc_cache,\narch/x86/kvm/mmu/mmu.c-1848-\t\t   \u0026vcpu-\u003earch.mmu_rmap_chunk_cache, slot, spte, gfn, access);\n--\narch/x86/kvm/mmu/mmu.c=3242=static int mmu_set_spte(struct kvm_vcpu *vcpu, struct kvm_memory_slot *slot,\n--\narch/x86/kvm/mmu/mmu.c-3308-\t\tWARN_ON_ONCE(ret == RET_PF_SPURIOUS);\narch/x86/kvm/mmu/mmu.c:3309:\t\trmap_add(vcpu, slot, sptep, gfn, pte_access);\narch/x86/kvm/mmu/mmu.c-3310-\t} else {\n--\narch/x86/kvm/mmu/mmu.c=7438=static void shadow_mmu_split_huge_page(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-7477-\t\tmmu_spte_set(sptep, spte);\narch/x86/kvm/mmu/mmu.c:7478:\t\t__rmap_add(kvm, cache, \u0026kvm-\u003earch.split_rmap_chunk_cache, slot,\narch/x86/kvm/mmu/mmu.c-7479-\t\t\t   sptep, gfn, sp-\u003erole.access);\n"
}

9/2 2026/11/06 06:39 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 22383
							output: 36
							thoughts: 15
						

Thoughts:
Okay, here's my attempt at summarizing that thought process, tailored for an expert audience:

**Analyzing the `slot_rmap_walk_next` Function Call**

Alright, so the first thing I need to do is get my head around this `slot_rmap_walk_next` function call. My primary goal is to understand its behavior in the context of the larger system. I'm assuming that since it's called `rmap`, it's likely related to reverse mappings, perhaps memory management, page tables, or some kind of resource tracking. "Slot" is an interesting name. It's likely a specific data structure, possibly an entry in an array or a bitfield. I need to figure out what data structure this 'slot' is associated with. The function name implies some sort of iteration, but I don’t know what is being iterated, and what is the 'next' it is retrieving. Is it stepping through a specific data structure, traversing a tree, or navigating a linked list? My first step is to dig into the function definition. From there I'll see what variables are being passed to it and what it returns and, of course, where it's called from and how that affects the larger function.



10/2 2026/11/06 06:41 tool grepper
0m Args:
{
  "Expression": "slot_rmap_walk_",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/mmu/mmu.c=1625=static bool kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,\n--\narch/x86/kvm/mmu/mmu.c-1630-\narch/x86/kvm/mmu/mmu.c:1631:struct slot_rmap_walk_iterator {\narch/x86/kvm/mmu/mmu.c-1632-\t/* input fields. */\n--\narch/x86/kvm/mmu/mmu.c-1648-\narch/x86/kvm/mmu/mmu.c:1649:static void rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator,\narch/x86/kvm/mmu/mmu.c-1650-\t\t\t\t int level)\n--\narch/x86/kvm/mmu/mmu.c-1660-\narch/x86/kvm/mmu/mmu.c:1661:static void slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,\narch/x86/kvm/mmu/mmu.c-1662-\t\t\t\tconst struct kvm_memory_slot *slot,\n--\narch/x86/kvm/mmu/mmu.c-1674-\narch/x86/kvm/mmu/mmu.c:1675:static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)\narch/x86/kvm/mmu/mmu.c-1676-{\n--\narch/x86/kvm/mmu/mmu.c-1679-\narch/x86/kvm/mmu/mmu.c:1680:static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)\narch/x86/kvm/mmu/mmu.c-1681-{\n--\narch/x86/kvm/mmu/mmu.c-1714-\t   _start_gfn, _end_gfn, _iter_)\t\t\t\t\\\narch/x86/kvm/mmu/mmu.c:1715:\tfor (slot_rmap_walk_init(_iter_, _slot_, _start_level_,\t\t\\\narch/x86/kvm/mmu/mmu.c-1716-\t\t\t\t _end_level_, _start_gfn, _end_gfn);\t\\\narch/x86/kvm/mmu/mmu.c:1717:\t     slot_rmap_walk_okay(_iter_);\t\t\t\t\\\narch/x86/kvm/mmu/mmu.c:1718:\t     slot_rmap_walk_next(_iter_))\narch/x86/kvm/mmu/mmu.c-1719-\n--\narch/x86/kvm/mmu/mmu.c=1725=static __always_inline bool __walk_slot_rmaps(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-1732-{\narch/x86/kvm/mmu/mmu.c:1733:\tstruct slot_rmap_walk_iterator iterator;\narch/x86/kvm/mmu/mmu.c-1734-\n"
}

11/2 2026/11/06 06:41 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 23583
							output: 37
							thoughts: 69
						

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

**Diving into the `rmap` Code**

Okay, so I'm looking at `for_each_slot_rmap_range`. My first thought is to understand its internals. It's using `slot_rmap_walk_init`, `slot_rmap_walk_okay`, and `slot_rmap_walk_next`. That's the basic pattern, makes sense. Now, the real key to understanding its purpose is to see *where* this is used. I'll need to trace its callers, that's the only way to get a solid grasp of what it's trying to achieve. I'm going to track down every call to `for_each_slot_rmap_range` and, of course, the underlying `__walk_slot_rmaps` to get the whole picture. Let's see what the code's doing!



12/2 2026/11/06 06:42 tool grepper
0m Args:
{
  "Expression": "__walk_slot_rmaps",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/mmu/mmu.c=1721=typedef bool (*slot_rmaps_handler) (struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-1724-\narch/x86/kvm/mmu/mmu.c:1725:static __always_inline bool __walk_slot_rmaps(struct kvm *kvm,\narch/x86/kvm/mmu/mmu.c-1726-\t\t\t\t\t      const struct kvm_memory_slot *slot,\n--\narch/x86/kvm/mmu/mmu.c=1758=static __always_inline bool walk_slot_rmaps(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-1763-{\narch/x86/kvm/mmu/mmu.c:1764:\treturn __walk_slot_rmaps(kvm, slot, fn, start_level, end_level,\narch/x86/kvm/mmu/mmu.c-1765-\t\t\t\t slot-\u003ebase_gfn, slot-\u003ebase_gfn + slot-\u003enpages - 1,\n--\narch/x86/kvm/mmu/mmu.c=1777=static bool __kvm_rmap_zap_gfn_range(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-1781-{\narch/x86/kvm/mmu/mmu.c:1782:\treturn __walk_slot_rmaps(kvm, slot, kvm_zap_rmap,\narch/x86/kvm/mmu/mmu.c-1783-\t\t\t\t PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,\n--\narch/x86/kvm/mmu/mmu.c=2712=static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)\n--\narch/x86/kvm/mmu/mmu.c-2731- * batched.  Doing so would require adding an invalid_list argument\narch/x86/kvm/mmu/mmu.c:2732: * all the way down to __walk_slot_rmaps().\narch/x86/kvm/mmu/mmu.c-2733- */\n--\narch/x86/kvm/mmu/mmu.c=7570=static void kvm_shadow_mmu_try_split_huge_pages(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-7583-\tfor (level = KVM_MAX_HUGEPAGE_LEVEL; level \u003e target_level; level--)\narch/x86/kvm/mmu/mmu.c:7584:\t\t__walk_slot_rmaps(kvm, slot, shadow_mmu_try_split_huge_pages,\narch/x86/kvm/mmu/mmu.c-7585-\t\t\t\t  level, level, start, end - 1, true, true, false);\n"
}

13/2 2026/11/06 06:42 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 24708
							output: 37
							thoughts: 30
						

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

**Investigating Call Sites of Rmap Traversal Functions**

Okay, so I'm thinking, let's get a handle on the current landscape. Specifically, I need to understand where `walk_slot_rmaps` and `for_each_slot_rmap_range` are being *used* within the codebase. I need to know where these functions are called from, what contexts they're invoked in, and what other code paths are interacting with these important Rmap-related functions. This analysis will give me critical insights into potential performance bottlenecks, areas for optimization, or possibly even risks related to these fundamental memory management operations. Basically, I want the full picture of the rmap-based logic usage.



14/2 2026/11/06 06:43 tool grepper
0m Args:
{
  "Expression": "walk_slot_rmaps\\(",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/mmu/mmu.c=1721=typedef bool (*slot_rmaps_handler) (struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-1724-\narch/x86/kvm/mmu/mmu.c:1725:static __always_inline bool __walk_slot_rmaps(struct kvm *kvm,\narch/x86/kvm/mmu/mmu.c-1726-\t\t\t\t\t      const struct kvm_memory_slot *slot,\n--\narch/x86/kvm/mmu/mmu.c-1757-\narch/x86/kvm/mmu/mmu.c:1758:static __always_inline bool walk_slot_rmaps(struct kvm *kvm,\narch/x86/kvm/mmu/mmu.c-1759-\t\t\t\t\t    const struct kvm_memory_slot *slot,\n--\narch/x86/kvm/mmu/mmu.c-1763-{\narch/x86/kvm/mmu/mmu.c:1764:\treturn __walk_slot_rmaps(kvm, slot, fn, start_level, end_level,\narch/x86/kvm/mmu/mmu.c-1765-\t\t\t\t slot-\u003ebase_gfn, slot-\u003ebase_gfn + slot-\u003enpages - 1,\n--\narch/x86/kvm/mmu/mmu.c=1769=static __always_inline bool walk_slot_rmaps_4k(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-1773-{\narch/x86/kvm/mmu/mmu.c:1774:\treturn walk_slot_rmaps(kvm, slot, fn, PG_LEVEL_4K, PG_LEVEL_4K, flush_on_yield);\narch/x86/kvm/mmu/mmu.c-1775-}\n--\narch/x86/kvm/mmu/mmu.c=1777=static bool __kvm_rmap_zap_gfn_range(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-1781-{\narch/x86/kvm/mmu/mmu.c:1782:\treturn __walk_slot_rmaps(kvm, slot, kvm_zap_rmap,\narch/x86/kvm/mmu/mmu.c-1783-\t\t\t\t PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,\n--\narch/x86/kvm/mmu/mmu.c=2712=static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)\n--\narch/x86/kvm/mmu/mmu.c-2731- * batched.  Doing so would require adding an invalid_list argument\narch/x86/kvm/mmu/mmu.c:2732: * all the way down to __walk_slot_rmaps().\narch/x86/kvm/mmu/mmu.c-2733- */\n--\narch/x86/kvm/mmu/mmu.c=7332=void kvm_mmu_slot_remove_write_access(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-7337-\t\twrite_lock(\u0026kvm-\u003emmu_lock);\narch/x86/kvm/mmu/mmu.c:7338:\t\twalk_slot_rmaps(kvm, memslot, slot_rmap_write_protect,\narch/x86/kvm/mmu/mmu.c-7339-\t\t\t\tstart_level, KVM_MAX_HUGEPAGE_LEVEL, false);\n--\narch/x86/kvm/mmu/mmu.c=7570=static void kvm_shadow_mmu_try_split_huge_pages(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-7583-\tfor (level = KVM_MAX_HUGEPAGE_LEVEL; level \u003e target_level; level--)\narch/x86/kvm/mmu/mmu.c:7584:\t\t__walk_slot_rmaps(kvm, slot, shadow_mmu_try_split_huge_pages,\narch/x86/kvm/mmu/mmu.c-7585-\t\t\t\t  level, level, start, end - 1, true, true, false);\n--\narch/x86/kvm/mmu/mmu.c=7681=static void kvm_rmap_zap_collapsible_sptes(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-7687-\t */\narch/x86/kvm/mmu/mmu.c:7688:\tif (walk_slot_rmaps(kvm, slot, kvm_mmu_zap_collapsible_spte,\narch/x86/kvm/mmu/mmu.c-7689-\t\t\t    PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL - 1, true))\n"
}

15/2 2026/11/06 06:43 llm patch-evaluator
3m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 26319
							output: 37
							thoughts: 15
						

Thoughts:
Okay, let's dive into this. Here's my take on those thoughts, as if they're my own:

**Investigating the `memslot_rmap_alloc` Call**

Alright, time to get my hands dirty. I need to understand what's happening within the `memslot_rmap_alloc` function. My mental process is going to start from a high-level view and gradually drill down. First, I'm thinking, this allocation suggests the system is setting up a memory mapping slot, probably related to a region's reverse mapping. This likely means some kind of page table management is involved, and I'll need to figure out where this fits into the overall memory management scheme. I'll need to see what this function does, what it is called from, and if I have existing knowledge about this specific area, how I can use that to my benefit. From there I can determine how this fits into the big picture. I'll be looking for clues in the surrounding code that inform this. I wonder if there are any specific structures or contexts being passed into this function, that will be my next area of focus. I need to understand the function's arguments. Are there any error conditions that are being returned and how are they being handled. After that, I'm probably going to need to look at the caller, and what the purpose of the call is.



16/2 2026/11/06 06:47 tool grepper
0m Args:
{
  "Expression": "memslot_rmap_alloc",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/mmu/mmu.c=4208=static int mmu_first_shadow_root_alloc(struct kvm *kvm)\n--\narch/x86/kvm/mmu/mmu.c-4251-\t\t\t */\narch/x86/kvm/mmu/mmu.c:4252:\t\t\tr = memslot_rmap_alloc(slot, slot-\u003enpages);\narch/x86/kvm/mmu/mmu.c-4253-\t\t\tif (r)\n--\narch/x86/kvm/x86.c=10169=void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)\n--\narch/x86/kvm/x86.c-10182-\narch/x86/kvm/x86.c:10183:int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)\narch/x86/kvm/x86.c-10184-{\n--\narch/x86/kvm/x86.c=10204=static int kvm_alloc_memslot_metadata(struct kvm *kvm,\n--\narch/x86/kvm/x86.c-10217-\tif (kvm_memslots_have_rmaps(kvm)) {\narch/x86/kvm/x86.c:10218:\t\tr = memslot_rmap_alloc(slot, npages);\narch/x86/kvm/x86.c-10219-\t\tif (r)\n--\narch/x86/kvm/x86.h=532=void __user *__x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,\narch/x86/kvm/x86.h-533-\t\t\t\t     u32 size);\narch/x86/kvm/x86.h:534:int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages);\narch/x86/kvm/x86.h-535-\n"
}

17/2 2026/11/06 06:47 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 27253
							output: 37
							thoughts: 61
						

Thoughts:
Here's my summary, as if I were thinking it:

**Investigating KVM Memory Slot Management**

Okay, so I'm looking at `memslot_rmap_alloc`. It's a non-static function, declared in `arch/x86/kvm/x86.h`.  That's straightforward enough. Now, I need to understand its counterpart. I wonder if there's a corresponding `memslot_rmap_free` function... yes, there is! Now, the real question becomes: who's calling it? Let me check the callers of `memslot_rmap_free` to get a better sense of how memory slots are being deallocated. This should give me a good handle on its usage patterns and any potential areas of concern.



18/2 2026/11/06 06:48 tool grepper
0m Args:
{
  "Expression": "memslot_rmap_free",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/x86.c=10144=static unsigned long memslot_rmap_nr_chunks(struct kvm_memory_slot *slot,\n--\narch/x86/kvm/x86.c-10150-\narch/x86/kvm/x86.c:10151:static void memslot_rmap_free(struct kvm_memory_slot *slot)\narch/x86/kvm/x86.c-10152-{\n--\narch/x86/kvm/x86.c=10169=void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)\n--\narch/x86/kvm/x86.c-10172-\narch/x86/kvm/x86.c:10173:\tmemslot_rmap_free(slot);\narch/x86/kvm/x86.c-10174-\n--\narch/x86/kvm/x86.c=10183=int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)\n--\narch/x86/kvm/x86.c-10195-\t\tif (!slot-\u003earch.rmap[i]) {\narch/x86/kvm/x86.c:10196:\t\t\tmemslot_rmap_free(slot);\narch/x86/kvm/x86.c-10197-\t\t\treturn -ENOMEM;\n--\narch/x86/kvm/x86.c=10204=static int kvm_alloc_memslot_metadata(struct kvm *kvm,\n--\narch/x86/kvm/x86.c-10263-out_free:\narch/x86/kvm/x86.c:10264:\tmemslot_rmap_free(slot);\narch/x86/kvm/x86.c-10265-\n"
}

19/2 2026/11/06 06:48 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 28067
							output: 40
							thoughts: 43
						

Thoughts:
Here's my take on the thought process, from an expert's perspective:

**Diving into KVM Memory Management**

Okay, so `kvm_arch_free_memslot` is the cleanup function for memory slots, and it calls `memslot_rmap_free`. That's standard practice, but it's always worth a quick audit of the call paths. Where does that function fit into the broader scheme? Specifically, I need to understand how freeing this memory slot ties into the shadow MMU, and particularly huge page handling. I'm going to quickly check `shadow_mmu_split_huge_page`. My intuition is this function is probably invoked when deallocating a memslot that may contain a split huge page within a guest's memory space, and it's essential to understand its callers to trace the exact cleanup steps. I need to understand the relationship between freeing a memslot and ensuring the shadow MMU is properly updated. This check on `shadow_mmu_split_huge_page` and its callers is the key to understand how memory slot deallocation is related to splitting huge pages. I'll need to follow the execution flow to see if there are any race conditions or data corruption possibilities, given the intricate nature of KVM memory management.



20/2 2026/11/06 06:48 tool grepper
0m Args:
{
  "Expression": "shadow_mmu_split_huge_page",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/mmu/mmu.c=2712=static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)\n--\narch/x86/kvm/mmu/mmu.c-2725- * is replaced with a shadow page SPTE with a fully populated page table,\narch/x86/kvm/mmu/mmu.c:2726: * which can happen from shadow_mmu_split_huge_page().  In this case,\narch/x86/kvm/mmu/mmu.c-2727- * no memory is unmapped across the change to the page tables and no\n--\narch/x86/kvm/mmu/mmu.c=7411=static struct kvm_mmu_page *shadow_mmu_get_sp_for_split(struct kvm *kvm, u64 *huge_sptep)\n--\narch/x86/kvm/mmu/mmu.c-7437-\narch/x86/kvm/mmu/mmu.c:7438:static void shadow_mmu_split_huge_page(struct kvm *kvm,\narch/x86/kvm/mmu/mmu.c-7439-\t\t\t\t       const struct kvm_memory_slot *slot,\n--\narch/x86/kvm/mmu/mmu.c=7485=static int shadow_mmu_try_split_huge_page(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-7516-\narch/x86/kvm/mmu/mmu.c:7517:\tshadow_mmu_split_huge_page(kvm, slot, huge_sptep);\narch/x86/kvm/mmu/mmu.c-7518-\n"
}

21/2 2026/11/06 06:48 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 28909
							output: 45
							thoughts: 38
						

Thoughts:
Here's my analysis of the provided prompt, followed by a summary as you requested:

The prompt is directing me to analyze a code context related to a virtual machine (likely KVM, given the context). It's asking me to track down the calls to specific functions: `shadow_mmu_try_split_huge_page` and `kvm_shadow_mmu_try_split_huge_pages`. My job is to summarize, in the first person, what my thought process would be as I investigate this code. I must assume the user has a deep understanding of the field.

Here's the summary:

**Digging into Huge Page Splitting**

Alright, let's get down to brass tacks. The prompt wants me to figure out where `shadow_mmu_try_split_huge_page` and `kvm_shadow_mmu_try_split_huge_pages` are called. This screams memory management within a KVM context. Clearly, we're talking about splitting huge pages. I'm going to start with the obvious: these functions are responsible for handling the breakdown of large memory regions, likely 2MB or 1GB pages, into smaller, more manageable units.

First thought: Why are we splitting these huge pages? The most common reasons are memory pressure or an operation that requires a more granular mapping. Maybe the guest is trying to write to a particular location that falls within a huge page. If the host doesn't have the appropriate permissions set for the virtual address translation, a split is necessary. Or perhaps it's a page fault, and the host needs to create a new, single-page mapping. Either way, this is happening within the shadow MMU framework.

Now, I'll need to trace the calls. I'm thinking, "Where would the shadow MMU need to intervene and potentially split a page?" My immediate plan is to use a code search (probably grep or an IDE's search function) to locate all instances where these functions are directly called. After that, I'll examine the call sites. From there I'll determine the context of each call to understand the triggers for huge page splitting. I will need to look into whether they are called from within the `kvm_mmu` module, or perhaps some related areas in the KVM core. This will shed light on what events or processes initiate the split. I need to be aware of the interplay between the shadow MMU, the guest's MMU, and the underlying host page tables. I'll need to figure out the synchronization that's involved, since splitting has to be thread-safe.

I'm also curious about the different function names. Is `shadow_mmu_try_split_huge_page` the base-level function, and `kvm_shadow_mmu_try_split_huge_pages` a KVM-specific wrapper or a batch operation? Or maybe the former is for handling the split of a single page, and the latter for splitting multiple pages at once. The naming convention likely provides clues.

Once I have a list of call sites, I'll carefully analyze each one. I'll be looking for patterns that trigger page splits, such as:

*   Page faults in the guest.
*   Memory write operations.
*   Guest page table updates.
*   Potentially, operations related to memory ballooning or live migration.

I will also expect to find some logic that determines when a split is *necessary* versus when it can be avoided. This likely involves checking for resource constraints, the presence of huge pages in the first place, and the configuration of the virtual machine.

With a good understanding of these call sites, I should have a solid grasp on how huge page splitting works within this part of the KVM infrastructure. This will provide some insights on performance considerations as well.



22/2 2026/11/06 06:48 tool grepper
0m Args:
{
  "Expression": "kvm_shadow_mmu_try_split_huge_pages",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/mmu/mmu.c=7524=static bool shadow_mmu_try_split_huge_pages(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-7569-\narch/x86/kvm/mmu/mmu.c:7570:static void kvm_shadow_mmu_try_split_huge_pages(struct kvm *kvm,\narch/x86/kvm/mmu/mmu.c-7571-\t\t\t\t\t\tconst struct kvm_memory_slot *slot,\n--\narch/x86/kvm/mmu/mmu.c=7589=void kvm_mmu_try_split_huge_pages(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-7597-\tif (kvm_memslots_have_rmaps(kvm))\narch/x86/kvm/mmu/mmu.c:7598:\t\tkvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);\narch/x86/kvm/mmu/mmu.c-7599-\n--\narch/x86/kvm/mmu/mmu.c=7608=void kvm_mmu_slot_try_split_huge_pages(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-7619-\t\twrite_lock(\u0026kvm-\u003emmu_lock);\narch/x86/kvm/mmu/mmu.c:7620:\t\tkvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);\narch/x86/kvm/mmu/mmu.c-7621-\t\twrite_unlock(\u0026kvm-\u003emmu_lock);\n"
}

23/2 2026/11/06 06:48 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 30317
							output: 41
							thoughts: 66
						

Thoughts:
Here's my summary, as if I were thinking it:

**Examining Huge Page Splitting in KVM on x86**

Alright, let's dive into this. I'm looking at `arch/x86/kvm/mmu/mmu.c`. I need to understand how the huge page splitting is handled, so I want to understand these functions. Specifically, `kvm_mmu_try_split_huge_pages` and `kvm_mmu_slot_try_split_huge_pages`. They're not declared as `static`, which immediately tells me they might be called from somewhere outside this particular file. Now, the next logical step for me is to trace the call paths. I need to find out *who* is calling these functions to get a better grasp of how the huge page splitting is triggered and managed within the KVM hypervisor on x86. This will reveal the context and purpose of these splitting attempts, whether it's related to memory pressure, virtual machine operations, or some other aspect of KVM's memory management.



24/2 2026/11/06 06:49 tool grepper
0m Args:
{
  "Expression": "kvm_mmu.*split_huge_pages",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/mmu.h=120=void kvm_mmu_slot_remove_write_access(struct kvm *kvm,\n--\narch/x86/kvm/mmu.h-122-\t\t\t\t      int start_level);\narch/x86/kvm/mmu.h:123:void kvm_mmu_slot_try_split_huge_pages(struct kvm *kvm,\narch/x86/kvm/mmu.h-124-\t\t\t\t       const struct kvm_memory_slot *memslot,\narch/x86/kvm/mmu.h-125-\t\t\t\t       int target_level);\narch/x86/kvm/mmu.h:126:void kvm_mmu_try_split_huge_pages(struct kvm *kvm,\narch/x86/kvm/mmu.h-127-\t\t\t\t  const struct kvm_memory_slot *memslot,\n--\narch/x86/kvm/mmu/mmu.c=1543=void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-1562-\t\tif (READ_ONCE(eager_page_split))\narch/x86/kvm/mmu/mmu.c:1563:\t\t\tkvm_mmu_try_split_huge_pages(kvm, slot, start, end + 1, PG_LEVEL_4K);\narch/x86/kvm/mmu/mmu.c-1564-\n--\narch/x86/kvm/mmu/mmu.c=7570=static void kvm_shadow_mmu_try_split_huge_pages(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-7588-/* Must be called with the mmu_lock held in write-mode. */\narch/x86/kvm/mmu/mmu.c:7589:void kvm_mmu_try_split_huge_pages(struct kvm *kvm,\narch/x86/kvm/mmu/mmu.c-7590-\t\t\t\t   const struct kvm_memory_slot *memslot,\n--\narch/x86/kvm/mmu/mmu.c-7603-\t * A TLB flush is unnecessary at this point for the same reasons as in\narch/x86/kvm/mmu/mmu.c:7604:\t * kvm_mmu_slot_try_split_huge_pages().\narch/x86/kvm/mmu/mmu.c-7605-\t */\n--\narch/x86/kvm/mmu/mmu.c-7607-\narch/x86/kvm/mmu/mmu.c:7608:void kvm_mmu_slot_try_split_huge_pages(struct kvm *kvm,\narch/x86/kvm/mmu/mmu.c-7609-\t\t\t\t\tconst struct kvm_memory_slot *memslot,\n--\narch/x86/kvm/x86.c=10332=static void kvm_mmu_slot_apply_flags(struct kvm *kvm,\n--\narch/x86/kvm/x86.c-10393-\t\tif (READ_ONCE(eager_page_split))\narch/x86/kvm/x86.c:10394:\t\t\tkvm_mmu_slot_try_split_huge_pages(kvm, new, PG_LEVEL_4K);\narch/x86/kvm/x86.c-10395-\n"
}

25/2 2026/11/06 06:49 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 31635
							output: 42
							thoughts: 157
						

Thoughts:
**My Investigation into KVM Huge Page Splitting**

Okay, so it looks like the `kvm_mmu_slot_try_split_huge_pages` function is getting called when dirty logging is enabled. Specifically, it's triggered by `kvm_mmu_slot_apply_flags`, which is doing some sort of "eager page splitting". Interesting. And `kvm_arch_mmu_enable_log_dirty_pt_masked` also calls `kvm_mmu_try_split_huge_pages` directly. This makes sense; dirty logging is a primary reason to split huge pages to allow tracking of modifications at a finer granularity.

Now, I also see that there's this `kvm_mmu_rmaps_stat_show` function, and it's exposed through debugfs. Hmm, that's potentially useful for getting stats related to this page splitting behavior. I'm curious, where exactly is this debugfs entry? I need to figure out the path. Let's do a quick `grep` for `kvm_mmu_rmaps_stat_show` or the name of the debugfs file that exposes it. This should quickly point me to the relevant debugfs directory. Knowing where this is exposed will allow me to access and analyze the rmap stats, which will be useful.



26/2 2026/11/06 06:49 tool grepper
0m Args:
{
  "Expression": "kvm_mmu_rmaps_stat_show",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/debugfs.c=89=static void kvm_mmu_rmaps_stat_level(struct kvm_memory_slot *slot, int level,\n--\narch/x86/kvm/debugfs.c-117-\narch/x86/kvm/debugfs.c:118:static int kvm_mmu_rmaps_stat_show(struct seq_file *m, void *v)\narch/x86/kvm/debugfs.c-119-{\n--\narch/x86/kvm/debugfs.c=178=static int kvm_mmu_rmaps_stat_open(struct inode *inode, struct file *file)\n--\narch/x86/kvm/debugfs.c-185-\narch/x86/kvm/debugfs.c:186:\tr = single_open(file, kvm_mmu_rmaps_stat_show, kvm);\narch/x86/kvm/debugfs.c-187-\tif (r \u003c 0)\n"
}

27/2 2026/11/06 06:49 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 32403
							output: 39
							thoughts: 31
						

Thoughts:
Okay, here's my interpretation of that thought process, tailored for an expert audience:

**Investigating Memory Cache Top-Up Behavior**

Alright, time to dive into `mmu_topup_memory_caches`. I need to understand this function's role. My immediate thought is, where is this thing actually being *used*? I need to trace its call graph to see what's triggering its execution and in what contexts. Knowing the calling functions is absolutely critical to understanding the *why* behind this cache top-up operation. From there, I can start to infer the conditions that lead to its invocation, and how this relates to overall system performance and resource allocation. No point in analyzing the function itself in isolation, gotta see it in action.



28/2 2026/11/06 06:50 tool grepper
0m Args:
{
  "Expression": "mmu_topup_memory_caches",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/mmu/mmu.c=591=static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)\n--\narch/x86/kvm/mmu/mmu.c-605-\narch/x86/kvm/mmu/mmu.c:606:static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)\narch/x86/kvm/mmu/mmu.c-607-{\n--\narch/x86/kvm/mmu/mmu.c=4988=static int direct_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)\n--\narch/x86/kvm/mmu/mmu.c-5002-\narch/x86/kvm/mmu/mmu.c:5003:\tr = mmu_topup_memory_caches(vcpu, false);\narch/x86/kvm/mmu/mmu.c-5004-\tif (r)\n--\narch/x86/kvm/mmu/mmu.c=5083=static int kvm_tdp_mmu_page_fault(struct kvm_vcpu *vcpu,\n--\narch/x86/kvm/mmu/mmu.c-5094-\narch/x86/kvm/mmu/mmu.c:5095:\tr = mmu_topup_memory_caches(vcpu, false);\narch/x86/kvm/mmu/mmu.c-5096-\tif (r)\n--\narch/x86/kvm/mmu/mmu.c=5328=int kvm_tdp_mmu_map_private_pfn(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)\n--\narch/x86/kvm/mmu/mmu.c-5375-\narch/x86/kvm/mmu/mmu.c:5376:\t\tr = mmu_topup_memory_caches(vcpu, false);\narch/x86/kvm/mmu/mmu.c-5377-\t\tif (r)\n--\narch/x86/kvm/mmu/mmu.c=6394=int kvm_mmu_load(struct kvm_vcpu *vcpu)\n--\narch/x86/kvm/mmu/mmu.c-6397-\narch/x86/kvm/mmu/mmu.c:6398:\tr = mmu_topup_memory_caches(vcpu, !vcpu-\u003earch.mmu-\u003eroot_role.direct);\narch/x86/kvm/mmu/mmu.c-6399-\tif (r)\n--\narch/x86/kvm/mmu/paging_tmpl.h=816=static int FNAME(page_fault)(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)\n--\narch/x86/kvm/mmu/paging_tmpl.h-849-\narch/x86/kvm/mmu/paging_tmpl.h:850:\tr = mmu_topup_memory_caches(vcpu, true);\narch/x86/kvm/mmu/paging_tmpl.h-851-\tif (r)\n"
}

29/2 2026/11/06 06:50 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 33534
							output: 37
							thoughts: 2693
						

Thoughts:
**Focus Symbol Selection for KVM MMU Changes**

Okay, so I'm diving into this KVM page fault hot path, and my initial thought is, "Wait, `mmu_topup_memory_caches` is called on *every* fault? That's not what we want to focus on." The goal here isn't to pick functions that are universally called in the kernel, but instead to pinpoint the code *specific* to the KVM MMU changes. We're trying to prevent diluting the fuzzing effort.

I need to make sure I don't select generic functions like allocators/deallocators, page fault handlers and the like. Instead, I need to focus on functions implementing *specific feature logic or entrypoints*.

First, I need to check which functions in the diff are actually symbols in `vmlinux`. So, I'm checking what's *non*-static. `memslot_rmap_alloc` looks promising, and so does `memslot_rmap_free` and I should also verify any functions that might be inlined.

Now I'm looking at `mmu.c`. The altered functions here are `memslot_rmap_alloc`, `kvm_mmu_slot_try_split_huge_pages`, `kvm_mmu_try_split_huge_pages`, and `kvm_mmu_slot_remove_write_access` - and, importantly, the static ones that are not inlined like `gfn_to_rmap_alloc`, `__rmap_add`, `rmap_add`, `shadow_mmu_split_huge_page`, `topup_split_caches`, `kvm_mmu_rmaps_stat_level`, `kvm_mmu_rmaps_stat_show`.

I need to check *every* modified/added function here, so I'm doing that systematically: I want to know if it is static, and if the function is not static, what its callers are and are they important entrypoints.

So, I check if `gfn_to_rmap_alloc`, `__rmap_add`, and `rmap_add` are static. Yes, they are. But are they inlined? `__rmap_add` calls `rmap_add` and `shadow_mmu_split_huge_page`. `rmap_add` is in `mmu_set_spte`, but `shadow_mmu_split_huge_page` is called in `shadow_mmu_try_split_huge_page`, which is called by `kvm_mmu_try_split_huge_pages` and `kvm_mmu_slot_try_split_huge_pages`.

I'm thinking about `slot_rmap_walk_next`, which is `static`. It calls `__walk_slot_rmaps`, which is `__always_inline`. This is a bit tricky, but I *still* need to consider it: I must list it if it's exercising the new/modified logic. It seems critical.

`kvm_arch_free_memslot` calls `memslot_rmap_free` and I want to list this one, since `memslot_rmap_free` is a modified function.

`kvm_mmu_rmaps_stat_show` and `kvm_mmu_rmaps_stat_level` are both altered, so I should list those.

Let's summarize:
1. `memslot_rmap_alloc`
2. `memslot_rmap_free`
3. `gfn_to_rmap_alloc`
4. `slot_rmap_walk_next`
5. `kvm_mmu_rmaps_stat_show`
6. `kvm_mmu_rmaps_stat_level`
7. `shadow_mmu_split_huge_page`
8. `kvm_mmu_slot_try_split_huge_pages`
9. `kvm_arch_free_memslot`

And finally, `gfn_to_rmap` - I need to make sure I don't include that if it's too generic. I need to make sure it's not a common entrypoint, or something like that.



30/2 2026/11/06 06:50 tool grepper
0m Args:
{
  "Expression": "gfn_to_rmap\\(",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/mmu/mmu.c=1237=unsigned int pte_list_count(struct kvm_rmap_head *rmap_head)\n--\narch/x86/kvm/mmu/mmu.c-1251-/*\narch/x86/kvm/mmu/mmu.c:1252: * Returned by gfn_to_rmap() for heads in a chunk that hasn't been allocated.\narch/x86/kvm/mmu/mmu.c-1253- * Readers see an empty rmap, and only __rmap_add() writes to a head that may\n--\narch/x86/kvm/mmu/mmu.c=1265=static struct kvm_rmap_head *__idx_to_rmap(const struct kvm_memory_slot *slot,\n--\narch/x86/kvm/mmu/mmu.c-1280-\narch/x86/kvm/mmu/mmu.c:1281:static struct kvm_rmap_head *gfn_to_rmap(gfn_t gfn, int level,\narch/x86/kvm/mmu/mmu.c-1282-\t\t\t\t\t const struct kvm_memory_slot *slot)\n--\narch/x86/kvm/mmu/mmu.c=1312=static void rmap_remove(struct kvm *kvm, u64 *spte)\n--\narch/x86/kvm/mmu/mmu.c-1330-\tslot = __gfn_to_memslot(slots, gfn);\narch/x86/kvm/mmu/mmu.c:1331:\trmap_head = gfn_to_rmap(gfn, sp-\u003erole.level, slot);\narch/x86/kvm/mmu/mmu.c-1332-\n--\narch/x86/kvm/mmu/mmu.c=1497=static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-1510-\twhile (mask) {\narch/x86/kvm/mmu/mmu.c:1511:\t\trmap_head = gfn_to_rmap(slot-\u003ebase_gfn + gfn_offset + __ffs(mask),\narch/x86/kvm/mmu/mmu.c-1512-\t\t\t\t\tPG_LEVEL_4K, slot);\n--\narch/x86/kvm/mmu/mmu.c=1520=static void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-1533-\twhile (mask) {\narch/x86/kvm/mmu/mmu.c:1534:\t\trmap_head = gfn_to_rmap(slot-\u003ebase_gfn + gfn_offset + __ffs(mask),\narch/x86/kvm/mmu/mmu.c-1535-\t\t\t\t\tPG_LEVEL_4K, slot);\n--\narch/x86/kvm/mmu/mmu.c=1595=bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-1604-\t\tfor (i = min_level; i \u003c= KVM_MAX_HUGEPAGE_LEVEL; ++i) {\narch/x86/kvm/mmu/mmu.c:1605:\t\t\trmap_head = gfn_to_rmap(gfn, i, slot);\narch/x86/kvm/mmu/mmu.c-1606-\t\t\twrite_protected |= rmap_write_protect(rmap_head, true);\n--\narch/x86/kvm/mmu/mmu.c=1649=static void rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator,\n--\narch/x86/kvm/mmu/mmu.c-1657-\titerator-\u003eend_idx = gfn_to_index(iterator-\u003eend_gfn, slot-\u003ebase_gfn, level);\narch/x86/kvm/mmu/mmu.c:1658:\titerator-\u003ermap = gfn_to_rmap(iterator-\u003egfn, level, slot);\narch/x86/kvm/mmu/mmu.c-1659-}\n--\narch/x86/kvm/mmu/mmu.c=1851=static bool kvm_rmap_age_gfn_range(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-1879-\t\t     gfn += KVM_PAGES_PER_HPAGE(level)) {\narch/x86/kvm/mmu/mmu.c:1880:\t\t\trmap_head = gfn_to_rmap(gfn, level, range-\u003eslot);\narch/x86/kvm/mmu/mmu.c-1881-\t\t\trmap_val = kvm_rmap_lock_readonly(kvm, rmap_head);\n"
}

31/2 2026/11/06 06:50 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 38553
							output: 33
							thoughts: 123
						

Thoughts:
Okay, here's my understanding, tailored for an expert audience, as if I'm thinking it:

**Analyzing the Call Sites of `gfn_to_rmap` and Related Kconfig Dependencies**

Alright, I'm tracking the usage of `gfn_to_rmap`. I've noted down that it's crucial for several KVM x86 functions: `rmap_remove`, `kvm_mmu_write_protect_pt_masked`, `kvm_mmu_clear_dirty_pt_masked`, `kvm_mmu_slot_gfn_write_protect`, `rmap_walk_init_level`, and `kvm_rmap_age_gfn_range`. Seems like a core function in handling the Guest Physical Frame Number (GFN) to Reverse Map (rmap) translation. This suggests it's likely involved in critical memory management operations within the KVM hypervisor.

Now, because this code is obviously so integral to some core functionality, I need to check the compilation conditions. Specifically, I need to look at the relevant Kconfig options to determine if these functions are always enabled or under some specific feature flag. I'll need to dig into the `arch/x86/kvm/Kconfig` file to see what triggers the compilation of this particular code and related calls. This will help me understand its context and whether any prerequisites need to be met.



32/2 2026/11/06 06:51 tool grepper
0m Args:
{
  "Expression": "config KVM",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/Kconfig=18=if VIRTUALIZATION\narch/x86/kvm/Kconfig-19-\narch/x86/kvm/Kconfig:20:config KVM_X86\narch/x86/kvm/Kconfig-21-\tdef_tristate KVM if (KVM_INTEL != n || KVM_AMD != n)\n--\narch/x86/kvm/Kconfig-47-\narch/x86/kvm/Kconfig:48:config KVM\narch/x86/kvm/Kconfig-49-\ttristate \"Kernel-based Virtual Machine (KVM) support\"\n--\narch/x86/kvm/Kconfig-64-\narch/x86/kvm/Kconfig:65:config KVM_WERROR\narch/x86/kvm/Kconfig-66-\tbool \"Compile KVM with -Werror\"\n--\narch/x86/kvm/Kconfig-78-\narch/x86/kvm/Kconfig:79:config KVM_PRIVATE_MEMATTR_VM\narch/x86/kvm/Kconfig-80-\tbool \"Enable per-VM PRIVATE vs. SHARED attributes (for CoCo VMs)\"\n--\narch/x86/kvm/Kconfig-92-\narch/x86/kvm/Kconfig:93:config KVM_SW_PROTECTED_VM\narch/x86/kvm/Kconfig-94-\tbool \"Enable support for KVM software-protected VMs\"\n--\narch/x86/kvm/Kconfig-104-\narch/x86/kvm/Kconfig:105:config KVM_INTEL\narch/x86/kvm/Kconfig-106-\ttristate \"KVM for Intel (and compatible) processors support\"\n--\narch/x86/kvm/Kconfig-115-\narch/x86/kvm/Kconfig:116:config KVM_INTEL_PROVE_VE\narch/x86/kvm/Kconfig-117-        bool \"Check that guests do not receive #VE exceptions\"\n--\narch/x86/kvm/Kconfig=131=config X86_SGX_KVM\n--\narch/x86/kvm/Kconfig-142-\narch/x86/kvm/Kconfig:143:config KVM_INTEL_TDX\narch/x86/kvm/Kconfig-144-\tbool \"Intel Trust Domain Extensions (TDX) support\"\n--\narch/x86/kvm/Kconfig-153-\narch/x86/kvm/Kconfig:154:config KVM_AMD\narch/x86/kvm/Kconfig-155-\ttristate \"KVM for AMD processors support\"\n--\narch/x86/kvm/Kconfig-163-\narch/x86/kvm/Kconfig:164:config KVM_AMD_SEV\narch/x86/kvm/Kconfig-165-\tbool \"AMD Secure Encrypted Virtualization (SEV) support\"\n--\narch/x86/kvm/Kconfig-179-\narch/x86/kvm/Kconfig:180:config KVM_IOAPIC\narch/x86/kvm/Kconfig-181-\tbool \"I/O APIC, PIC, and PIT emulation\"\n--\narch/x86/kvm/Kconfig-189-\narch/x86/kvm/Kconfig:190:config KVM_SMM\narch/x86/kvm/Kconfig-191-\tbool \"System Management Mode emulation\"\n--\narch/x86/kvm/Kconfig-200-\narch/x86/kvm/Kconfig:201:config KVM_HYPERV\narch/x86/kvm/Kconfig-202-\tbool \"Support for Microsoft Hyper-V emulation\"\n--\narch/x86/kvm/Kconfig-214-\narch/x86/kvm/Kconfig:215:config KVM_XEN\narch/x86/kvm/Kconfig-216-\tbool \"Support for Xen hypercall interface\"\n--\narch/x86/kvm/Kconfig-223-\narch/x86/kvm/Kconfig:224:config KVM_PROVE_MMU\narch/x86/kvm/Kconfig-225-\tbool \"Prove KVM MMU correctness\"\n--\narch/x86/kvm/Kconfig-236-\narch/x86/kvm/Kconfig:237:config KVM_EXTERNAL_WRITE_TRACKING\narch/x86/kvm/Kconfig-238-\tbool\narch/x86/kvm/Kconfig-239-\narch/x86/kvm/Kconfig:240:config KVM_MAX_NR_VCPUS\narch/x86/kvm/Kconfig-241-\tint \"Maximum number of vCPUs per KVM guest\"\n"
}

33/2 2026/11/06 06:51 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 40307
							output: 39
							thoughts: 18
						

Thoughts:
Okay, let's dive into this. Here's my take on those thoughts, as if they're my own:

**Investigating the KVM x86 Makefile**

Alright, I'm thinking I need to understand something within the KVM architecture on x86, and my initial instinct is to go directly to the source. The Makefile, specifically the one located in `arch/x86/kvm/Makefile`, is where I'd expect to find the build instructions, dependencies, and ultimately, the logic for assembling the KVM components on that particular architecture. That's the most logical place to begin my investigation to understand, or modify something related to KVM's x86 implementation. Let's see what we can find.



34/2 2026/11/06 06:53 tool grepper
0m Args:
{
  "Expression": "debugfs\\.o|mmu\\.o",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/Makefile=8=kvm-y\t\t\t+= x86.o emulate.o irq.o lapic.o cpuid.o msrs.o pmu.o regs.o \\\narch/x86/kvm/Makefile:9:\t\t\t   mtrr.o debugfs.o mmu/mmu.o mmu/page_track.o mmu/spte.o\narch/x86/kvm/Makefile-10-\narch/x86/kvm/Makefile:11:kvm-$(CONFIG_X86_64) += mmu/tdp_iter.o mmu/tdp_mmu.o\narch/x86/kvm/Makefile-12-kvm-$(CONFIG_KVM_IOAPIC) += i8259.o i8254.o ioapic.o\n"
}

35/2 2026/11/06 06:53 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 40743
							output: 39
							thoughts: 178
						

Thoughts:
Okay, let me break this down.

**KVM Module Dependencies & Configuration Review**

Alright, so I'm looking at this build configuration: `kvm-y += x86.o emulate.o irq.o lapic.o cpuid.o msrs.o pmu.o regs.o mtrr.o debugfs.o mmu/mmu.o mmu/page_track.o mmu/spte.o` and `obj-$(CONFIG_KVM) += kvm.o`. Clearly, these are the core object files being linked into the KVM module.  The `x86.o` part makes it obvious this is x86-specific. I'm noting the standard KVM-related object files, alongside more granular modules that deal with emulation, interrupts, local APICs, and the CPUID instruction. The inclusion of MSR handling is expected, and the MMU-related modules (mmu.o, page_track.o, spte.o) are what I'd expect to see, particularly for x86.

Then, there are the `CONFIG_KVM`, `CONFIG_KVM_INTEL`, and `CONFIG_KVM_AMD` dependencies, which, of course, are required for KVM on x86, which is obvious.

Now, that `CONFIG_KVM_PROVE_MMU` debug config... that's interesting. I need to see what that's about. Let's check the `arch/x86/kvm/Kconfig` file and see what kind of MMU correctness checks it is offering. It looks like the KVM maintainers are serious about ensuring MMU correctness. This could be a very valuable debugging tool for complex KVM scenarios! I'm going to want to remember to check that out when I get the chance.



36/2 2026/11/06 06:53 tool read-file
0m Args:
{
  "File": "arch/x86/kvm/Kconfig",
  "FirstLine": 220,
  "LineCount": 20
}

Results:
{
  "Contents": " 220:\t\t  passing Xen hypercalls to userspace.\n 221:\t\n 222:\t\t  If in doubt, say \"N\".\n 223:\t\n 224:\tconfig KVM_PROVE_MMU\n 225:\t\tbool \"Prove KVM MMU correctness\"\n 226:\t\tdepends on DEBUG_KERNEL\n 227:\t\tdepends on KVM_X86\n 228:\t\tdepends on EXPERT\n 229:\t\thelp\n 230:\t\t  Enables runtime assertions in KVM's MMU that are too costly to enable\n 231:\t\t  in anything remotely resembling a production environment, e.g. this\n 232:\t\t  gates code that verifies a to-be-freed page table doesn't have any\n 233:\t\t  present SPTEs.\n 234:\t\n 235:\t\t  If in doubt, say \"N\".\n 236:\t\n 237:\tconfig KVM_EXTERNAL_WRITE_TRACKING\n 238:\t\tbool\n 239:\t\n"
}

37/2 2026/11/06 06:53 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 41645
							output: 38
							thoughts: 159
						

Thoughts:
**KVM Configuration Conundrum**

Okay, so I'm diving into KVM configuration, specifically for MMU fuzzing. `CONFIG_KVM_PROVE_MMU` is a really handy debugging tool, but I need to be clear on what *else* is required. It's not essential for compiling or running KVM, but what's the minimum set of configurations?

Obviously, I need `KVM` enabled, that's a given. But to actually get virtual machines running on x86, be it bare metal or virtualized, I need either `KVM_INTEL` or `KVM_AMD`. Hold on... what about `KVM_X86`? That feels like a potential red herring. Let me check its definition. Ah, right, `KVM_X86` is a dependency, it's defined as a tristate that's enabled only if *either* `KVM_INTEL` or `KVM_AMD` is *not* disabled.

Just to be absolutely certain, let's take a look at `arch/x86/kvm/Kconfig` from lines 15 to 45, just to be sure there are no other configurations I'm missing.



38/2 2026/11/06 06:53 tool read-file
0m Args:
{
  "File": "arch/x86/kvm/Kconfig",
  "FirstLine": 15,
  "LineCount": 40
}

Results:
{
  "Contents": "  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 VHOST_TASK\n  32:\t\tselect KVM_ASYNC_PF\n  33:\t\tselect USER_RETURN_NOTIFIER\n  34:\t\tselect SCHED_INFO\n  35:\t\tselect PERF_EVENTS\n  36:\t\tselect GUEST_PERF_EVENTS\n  37:\t\tselect PERF_GUEST_MEDIATED_PMU\n  38:\t\tselect HAVE_KVM_CPU_RELAX_INTERCEPT\n  39:\t\tselect VIRT_XFER_TO_GUEST_WORK\n  40:\t\tselect KVM_GENERIC_DIRTYLOG_READ_PROTECT\n  41:\t\tselect KVM_VFIO\n  42:\t\tselect HAVE_KVM_PM_NOTIFIER if PM\n  43:\t\tselect KVM_GENERIC_HARDWARE_ENABLING\n  44:\t\tselect KVM_GENERIC_PRE_FAULT_MEMORY\n  45:\t\tselect KVM_WERROR if WERROR\n  46:\t\tselect KVM_GUEST_MEMFD if X86_64\n  47:\t\n  48:\tconfig KVM\n  49:\t\ttristate \"Kernel-based Virtual Machine (KVM) support\"\n  50:\t\tdepends on X86_LOCAL_APIC\n  51:\t\thelp\n  52:\t\t  Support hosting fully virtualized guest machines using hardware\n  53:\t\t  virtualization extensions.  You will need a fairly recent\n  54:\t\t  processor equipped with virtualization extensions. You will also\n"
}

39/2 2026/11/06 06:53 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 42739
							output: 35
							thoughts: 332
						

Thoughts:
**Analyzing KVM Configuration Requirements**

Okay, so I'm looking at the core KVM configuration options. From what I understand, `CONFIG_KVM`, and then specifically `CONFIG_KVM_INTEL` or `CONFIG_KVM_AMD` are the primary ones we're dealing with. Then there's `CONFIG_KVM_PROVE_MMU`, which, if relevant, will be important to include for more robust MMU assertions. I have to be careful though, I need to stick to the instructions: I can't just make assumptions. I need to dive into the kernel configuration files, particularly the `Kconfig` files and `#ifdef` guards, to be absolutely sure. The instructions emphasize that I should also check "depends on" lines in the `Kconfig` files to make sure I don't miss any parent subsystem configs. And of course, strip the `CONFIG_` prefix when specifying the required options.

So, *definitely* `CONFIG_KVM` and either `CONFIG_KVM_INTEL` or `CONFIG_KVM_AMD` are essential. Now, I should double check to see if `KVM_PROVE_MMU` enables any interesting assertions. My next step will be to explore `arch/x86/kvm/mmu/mmu.c` and `debugfs.c`.

Based on `arch/x86/kvm/Makefile`, I see that `debugfs.o` and `mmu/mmu.o` are included in the compilation. I need to know if `debugfs.o` is conditionally compiled based on `CONFIG_KVM` and `CONFIG_DEBUG_FS`. I'm going to double check by inspecting both `arch/x86/kvm/Makefile` and `arch/x86/kvm/debugfs.c` to see how those are linked and conditionally included.



40/2 2026/11/06 06:54 tool grepper
0m Args:
{
  "Expression": "CONFIG_DEBUG_FS",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "no matches"
}

41/2 2026/11/06 06:54 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 43530
							output: 39
							thoughts: 19
						

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

**Diving into KVM Debugfs**

Okay, so I'm thinking, "Right, time to get a bit deeper into the weeds." The objective here is clearly to understand how KVM's debug filesystem, `debugfs`, interacts with the x86 architecture. Specifically, I'm going to focus my attention on `arch/x86/kvm/debugfs.c`. I expect to find the core implementation details related to exposing KVM internals and control mechanisms through this filesystem interface. I'm keen to see how they've handled security, how granular the controls are, and what aspects of the virtual machine's state are exposed for inspection and modification. I'll likely be looking for file operations, permission checks, and data structures involved in representing KVM state within the debugfs hierarchy. Time to dig in and see how well the design adheres to the principles of safe and performant kernel development.



42/2 2026/11/06 06:54 tool read-file
0m Args:
{
  "File": "arch/x86/kvm/debugfs.c",
  "FirstLine": 1,
  "LineCount": 40
}

Results:
{
  "Contents": "   1:\t// SPDX-License-Identifier: GPL-2.0-only\n   2:\t/*\n   3:\t * Kernel-based Virtual Machine driver for Linux\n   4:\t *\n   5:\t * Copyright 2016 Red Hat, Inc. and/or its affiliates.\n   6:\t */\n   7:\t#define pr_fmt(fmt) KBUILD_MODNAME \": \" fmt\n   8:\t\n   9:\t#include \u003clinux/kvm_host.h\u003e\n  10:\t#include \u003clinux/debugfs.h\u003e\n  11:\t#include \"lapic.h\"\n  12:\t#include \"mmu.h\"\n  13:\t#include \"mmu/mmu_internal.h\"\n  14:\t\n  15:\tstatic int vcpu_get_timer_advance_ns(void *data, u64 *val)\n  16:\t{\n  17:\t\tstruct kvm_vcpu *vcpu = (struct kvm_vcpu *) data;\n  18:\t\t*val = vcpu-\u003earch.apic-\u003elapic_timer.timer_advance_ns;\n  19:\t\treturn 0;\n  20:\t}\n  21:\t\n  22:\tDEFINE_SIMPLE_ATTRIBUTE(vcpu_timer_advance_ns_fops, vcpu_get_timer_advance_ns, NULL, \"%llu\\n\");\n  23:\t\n  24:\tstatic int vcpu_get_guest_mode(void *data, u64 *val)\n  25:\t{\n  26:\t\tstruct kvm_vcpu *vcpu = (struct kvm_vcpu *) data;\n  27:\t\t*val = vcpu-\u003estat.guest_mode;\n  28:\t\treturn 0;\n  29:\t}\n  30:\t\n  31:\tDEFINE_SIMPLE_ATTRIBUTE(vcpu_guest_mode_fops, vcpu_get_guest_mode, NULL, \"%lld\\n\");\n  32:\t\n  33:\tstatic int vcpu_get_tsc_offset(void *data, u64 *val)\n  34:\t{\n  35:\t\tstruct kvm_vcpu *vcpu = (struct kvm_vcpu *) data;\n  36:\t\t*val = vcpu-\u003earch.tsc_offset;\n  37:\t\treturn 0;\n  38:\t}\n  39:\t\n  40:\tDEFINE_SIMPLE_ATTRIBUTE(vcpu_tsc_offset_fops, vcpu_get_tsc_offset, NULL, \"%lld\\n\");\n"
}

43/2 2026/11/06 06:54 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 44442
							output: 267
							thoughts: 1240
						

Thoughts:
**Focusing on KVM Shadow MMU Rmap Refactoring for Fuzzing**

Okay, let's break this down. We're looking at a KVM patch and want to specify the right settings for fuzzing. I need to make sure we're targeting the right parts of the code to maximize the effectiveness of the fuzzing.

First, the core configs: `KVM`, `KVM_INTEL`, and `KVM_AMD` – standard for KVM on amd64. Easy. Now, the `FocusSymbols`. That's where it gets interesting. I need to identify the *specific* functions that implement the logic being added or altered, or are direct API entrypoints for the feature. And crucially, I need to *avoid* ubiquitous, lifecycle hot-paths. Things like general memory allocation and deallocation, core synchronization, and trap handlers are *out*. They'll just pollute the results.

Let's run through the functions from the patch, and assess them one by one, to make sure they're not too generic:

*   `memslot_rmap_alloc` and `memslot_rmap_free`: These are specific to KVM memory slot management, allocating and freeing the rmap structures. They are not ubiquitous.
*   `gfn_to_rmap_alloc`: A newly added function, clearly tied to shadow MMU rmap chunk allocation. Not ubiquitous.
*   `__rmap_add`: Altered function that includes a call to `gfn_to_rmap_alloc`, also not ubiquitous.
*   `slot_rmap_walk_next`: Part of the rmap iteration logic, and it's specifically for KVM's MMU operations (dirty logging, write protect, etc.). Again, KVM-specific.
*   `shadow_mmu_split_huge_page`: This is KVM specific huge page splitting. Not ubiquitous.
*   `kvm_mmu_rmaps_stat_level` and `kvm_mmu_rmaps_stat_show`: These relate to the debugfs statistics, which is important, but still KVM-specific.
*   `topup_split_caches`: This is for caching, and it is specific to KVM split caches.
*   `kvm_mmu_slot_try_split_huge_pages`: This is the entry point for the eager page splitting feature.

After a review, *none* of these look like general-purpose utility functions. They are *all* either directly part of the KVM MMU implementation or related to the rmap structures. They're not called by arbitrary non-KVM code, and they don't look like common kernel hot-paths. Good!

So, the focus symbols are:
*   `memslot_rmap_alloc`
*   `memslot_rmap_free`
*   `gfn_to_rmap_alloc`
*   `slot_rmap_walk_next`
*   `shadow_mmu_split_huge_page`
*   `kvm_mmu_slot_try_split_huge_pages`
*   `kvm_mmu_rmaps_stat_show`
*   `kvm_mmu_rmaps_stat_level`

Now, the `Reasoning`: I have to articulate *why* this patch warrants fuzzing. This patch is fundamentally refactoring KVM's shadow MMU rmaps, switching from flat arrays to sparse, chunked directories. This touches chunk allocation, release synchronization (`smp_store_release` / `READ_ONCE`), chunk skipping during iteration, memory caching for page splitting, and memory slot cleanup. This change impacts a lot of core MMU functionality, all reachable via KVM ioctls for memory regions, dirty logging, page splitting, and VM destruction, plus debugfs. Fuzzing can help us identify potential concurrency issues (concurrent reads and writes to rmap, for example), memory leaks from the new chunk management, any out-of-bounds access in the chunk calculations, and any assertion failures.

Therefore, `WorthFuzzing` is `true`. Let's feed that into `set-results`.



44/2 2026/11/06 06:54 tool set-results
0m Args:
{
  "EnableConfigs": [
    "KVM",
    "KVM_INTEL",
    "KVM_AMD"
  ],
  "FocusSymbols": [
    "memslot_rmap_alloc",
    "memslot_rmap_free",
    "gfn_to_rmap_alloc",
    "slot_rmap_walk_next",
    "shadow_mmu_split_huge_page",
    "kvm_mmu_slot_try_split_huge_pages",
    "kvm_mmu_rmaps_stat_show",
    "kvm_mmu_rmaps_stat_level"
  ],
  "Reasoning": "The patch converts KVM x86 shadow MMU reverse mapping (rmap) arrays into sparse two-level chunk directories allocated on demand. This touches core KVM memory management logic, introducing lockless chunk publication (smp_store_release/READ_ONCE), chunk-skipping iteration in slot_rmap_walk_next, rmap chunk caching during huge page splitting, and new memslot rmap allocation and deallocation paths. This code is fully reachable via KVM ioctls and debugfs, making it a high-value target for fuzzing.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "KVM",
    "KVM_INTEL",
    "KVM_AMD"
  ],
  "FocusSymbols": [
    "memslot_rmap_alloc",
    "memslot_rmap_free",
    "gfn_to_rmap_alloc",
    "slot_rmap_walk_next",
    "shadow_mmu_split_huge_page",
    "kvm_mmu_slot_try_split_huge_pages",
    "kvm_mmu_rmaps_stat_show",
    "kvm_mmu_rmaps_stat_level"
  ],
  "Reasoning": "The patch converts KVM x86 shadow MMU reverse mapping (rmap) arrays into sparse two-level chunk directories allocated on demand. This touches core KVM memory management logic, introducing lockless chunk publication (smp_store_release/READ_ONCE), chunk-skipping iteration in slot_rmap_walk_next, rmap chunk caching during huge page splitting, and new memslot rmap allocation and deallocation paths. This code is fully reachable via KVM ioctls and debugfs, making it a high-value target for fuzzing.",
  "WorthFuzzing": true
}

45/1 2026/11/06 06:54 action If
8m Args:
{
  "WorthFuzzing": true
}

Results:
null

46/2 2026/11/06 06:54 agent kmsan-evaluator
8m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch transitions KVM shadow MMU rmap tracking from monolithic arrays to on-demand allocated chunk pages (each holding KVM_RMAP_CHUNK_NR_HEADS rmap heads).\n\nAnalysis of memory initialization and user-facing data:\n1. The chunk directories (`slot-\u003earch.rmap[i]`) are allocated using `kvcalloc()`, which zeroes all chunk pointers.\n2. The rmap chunk pages are allocated via `kvm_mmu_memory_cache_alloc()` from `mmu_rmap_chunk_cache` and `split_rmap_chunk_cache`, both of which are explicitly configured with `gfp_zero = __GFP_ZERO`, ensuring that every newly allocated chunk is zero-filled.\n3. The fallback `kvm_empty_rmap_head` is declared as static storage and thus is zero-initialized.\n4. The rmaps stat debugfs handler allocates its counting buckets with `kcalloc()`.\n5. No uninitialized memory, struct fields, or padding are exposed or copied to user space.\n\nPotential bugs in this patch involve chunk indexing arithmetic, iterator walk logic, concurrent lockless chunk installation, or chunk deallocation (`free_page`), which could lead to out-of-bounds accesses, use-after-free, or synchronization errors. These risks are effectively detected by KASAN, LOCKDEP, and page debugging tools. Because there are no uninitialized memory access or info-leak risks, a dedicated KMSAN fuzzing session is not justified.",
  "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 5315a724060f567610297263a0938d976c4486c6
Author: syz-cluster <triage@syzkaller.com>
Date:   Fri Nov 6 06:25:41 2026 +0000

    syz-cluster: applied patch under review

diff --git a/arch/x86/include/asm/kvm_host.h b/arch/x86/include/asm/kvm_host.h
index 0378577d9d8bbf..4cc00dc83aba4d 100644
--- a/arch/x86/include/asm/kvm_host.h
+++ b/arch/x86/include/asm/kvm_host.h
@@ -431,6 +431,8 @@ struct kvm_rmap_head {
 	atomic_long_t val;
 };
 
+#define KVM_RMAP_CHUNK_NR_HEADS	(PAGE_SIZE / sizeof(struct kvm_rmap_head))
+
 struct kvm_pio_request {
 	unsigned long count;
 	int in;
@@ -785,6 +787,7 @@ struct kvm_vcpu_arch {
 	u64 pdptrs[4]; /* pae */
 
 	struct kvm_mmu_memory_cache mmu_pte_list_desc_cache;
+	struct kvm_mmu_memory_cache mmu_rmap_chunk_cache;
 	struct kvm_mmu_memory_cache mmu_shadow_page_cache;
 	struct kvm_mmu_memory_cache mmu_shadowed_info_cache;
 	struct kvm_mmu_memory_cache mmu_page_header_cache;
@@ -1044,7 +1047,13 @@ struct kvm_lpage_info {
 };
 
 struct kvm_arch_memory_slot {
-	struct kvm_rmap_head *rmap[KVM_NR_PAGE_SIZES];
+	/*
+	 * Per-level directories of rmap chunks, each chunk holding
+	 * KVM_RMAP_CHUNK_NR_HEADS rmap heads.  Chunks are allocated when KVM
+	 * adds the first SPTE to a head in the chunk's range.  A NULL chunk
+	 * means all of its heads are empty.
+	 */
+	struct kvm_rmap_head **rmap[KVM_NR_PAGE_SIZES];
 	struct kvm_lpage_info *lpage_info[KVM_NR_PAGE_SIZES - 1];
 	unsigned short *gfn_write_track;
 };
@@ -1418,6 +1427,17 @@ struct kvm_arch {
 #define SPLIT_DESC_CACHE_MIN_NR_OBJECTS (SPTE_ENT_PER_PAGE + 1)
 	struct kvm_mmu_memory_cache split_desc_cache;
 
+	/*
+	 * Memory cache used to allocate rmap chunks while splitting huge
+	 * pages.  The rmap heads of the lower level leaf SPTEs of one huge
+	 * page are contiguous, but span two chunks if the memslot's base gfn
+	 * is not aligned to the chunk size.
+	 *
+	 * Protected by kvm->slots_lock.
+	 */
+#define SPLIT_RMAP_CHUNK_CACHE_NR_OBJECTS 2
+	struct kvm_mmu_memory_cache split_rmap_chunk_cache;
+
 	gfn_t gfn_direct_bits;
 	int mirror_root_level;
 
diff --git a/arch/x86/kvm/debugfs.c b/arch/x86/kvm/debugfs.c
index 0074a56e45b44b..0cdb1ef1b18416 100644
--- a/arch/x86/kvm/debugfs.c
+++ b/arch/x86/kvm/debugfs.c
@@ -86,16 +86,43 @@ void kvm_arch_create_vcpu_debugfs(struct kvm_vcpu *vcpu, struct dentry *debugfs_
 
 static const char *kvm_lpage_str[KVM_NR_PAGE_SIZES] = { "4K", "2M", "1G" };
 
+static void kvm_mmu_rmaps_stat_level(struct kvm_memory_slot *slot, int level,
+				     unsigned int *cur)
+{
+	struct kvm_rmap_head **rmap = slot->arch.rmap[level - PG_LEVEL_4K];
+	unsigned long lpages = kvm_mmu_slot_lpages(slot, level);
+	struct kvm_rmap_head *chunk;
+	unsigned long l, nr;
+	unsigned int index;
+
+	for (l = 0; l < lpages; l += nr) {
+		nr = min(lpages - l, KVM_RMAP_CHUNK_NR_HEADS);
+		chunk = rmap[l / KVM_RMAP_CHUNK_NR_HEADS];
+
+		/* An unallocated chunk holds only empty rmaps. */
+		if (!chunk) {
+			cur[0] += nr;
+			continue;
+		}
+
+		for (index = 0; index < nr; index++) {
+			unsigned int bucket = fls(pte_list_count(&chunk[index]));
+
+			if (WARN_ON_ONCE(bucket >= RMAP_LOG_SIZE))
+				bucket = RMAP_LOG_SIZE - 1;
+			cur[bucket]++;
+		}
+	}
+}
+
 static int kvm_mmu_rmaps_stat_show(struct seq_file *m, void *v)
 {
-	struct kvm_rmap_head *rmap;
 	struct kvm *kvm = m->private;
 	struct kvm_memory_slot *slot;
 	struct kvm_memslots *slots;
-	unsigned int lpage_size, index;
 	/* Still small enough to be on the stack */
 	unsigned int *log[KVM_NR_PAGE_SIZES], *cur;
-	int i, j, k, l, ret;
+	int i, j, k, ret;
 
 	if (!kvm_memslots_have_rmaps(kvm))
 		return 0;
@@ -116,17 +143,8 @@ static int kvm_mmu_rmaps_stat_show(struct seq_file *m, void *v)
 
 		slots = __kvm_memslots(kvm, i);
 		kvm_for_each_memslot(slot, bkt, slots)
-			for (k = 0; k < KVM_NR_PAGE_SIZES; k++) {
-				rmap = slot->arch.rmap[k];
-				lpage_size = kvm_mmu_slot_lpages(slot, k + 1);
-				cur = log[k];
-				for (l = 0; l < lpage_size; l++) {
-					index = fls(pte_list_count(&rmap[l]));
-					if (WARN_ON_ONCE(index >= RMAP_LOG_SIZE))
-						index = RMAP_LOG_SIZE - 1;
-					cur[index]++;
-				}
-			}
+			for (k = 0; k < KVM_NR_PAGE_SIZES; k++)
+				kvm_mmu_rmaps_stat_level(slot, k + 1, log[k]);
 	}
 
 	write_unlock(&kvm->mmu_lock);
diff --git a/arch/x86/kvm/mmu/mmu.c b/arch/x86/kvm/mmu/mmu.c
index f4b12d6aef5593..1b958f66764c15 100644
--- a/arch/x86/kvm/mmu/mmu.c
+++ b/arch/x86/kvm/mmu/mmu.c
@@ -612,6 +612,17 @@ static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
 				       1 + PT64_ROOT_MAX_LEVEL + PTE_PREFETCH_NUM);
 	if (r)
 		return r;
+	/*
+	 * 1 rmap chunk for the faulting gfn and 1 per prefetched gfn.  Cap the
+	 * cache at that, as each object is a page.
+	 */
+	if (kvm_memslots_have_rmaps(vcpu->kvm)) {
+		r = __kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_rmap_chunk_cache,
+						 1 + PTE_PREFETCH_NUM,
+						 1 + PTE_PREFETCH_NUM);
+		if (r)
+			return r;
+	}
 	if (kvm_has_mirrored_tdp(vcpu->kvm)) {
 		r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_external_spt_cache,
 					       PT64_ROOT_MAX_LEVEL);
@@ -635,6 +646,7 @@ static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
 {
 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache);
+	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_rmap_chunk_cache);
 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache);
 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadowed_info_cache);
 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_external_spt_cache);
@@ -1236,13 +1248,65 @@ unsigned int pte_list_count(struct kvm_rmap_head *rmap_head)
 	return desc->tail_count + desc->spte_count;
 }
 
+/*
+ * Returned by gfn_to_rmap() for heads in a chunk that hasn't been allocated.
+ * Readers see an empty rmap, and only __rmap_add() writes to a head that may
+ * be empty, after allocating its chunk.
+ */
+static struct kvm_rmap_head kvm_empty_rmap_head;
+
+static struct kvm_rmap_head **
+rmap_chunkp(const struct kvm_memory_slot *slot, int level, unsigned long idx)
+{
+	return &slot->arch.rmap[level - PG_LEVEL_4K][idx / KVM_RMAP_CHUNK_NR_HEADS];
+}
+
+/* Returns NULL if the chunk holding the head hasn't been allocated. */
+static struct kvm_rmap_head *__idx_to_rmap(const struct kvm_memory_slot *slot,
+					   int level, unsigned long idx)
+{
+	struct kvm_rmap_head *chunk;
+
+	/*
+	 * Lockless walkers can observe a chunk being installed.  Pairs with
+	 * the smp_store_release() in gfn_to_rmap_alloc().
+	 */
+	chunk = READ_ONCE(*rmap_chunkp(slot, level, idx));
+	if (!chunk)
+		return NULL;
+
+	return &chunk[idx % KVM_RMAP_CHUNK_NR_HEADS];
+}
+
 static struct kvm_rmap_head *gfn_to_rmap(gfn_t gfn, int level,
 					 const struct kvm_memory_slot *slot)
 {
-	unsigned long idx;
+	struct kvm_rmap_head *rmap_head;
 
-	idx = gfn_to_index(gfn, slot->base_gfn, level);
-	return &slot->arch.rmap[level - PG_LEVEL_4K][idx];
+	rmap_head = __idx_to_rmap(slot, level,
+				  gfn_to_index(gfn, slot->base_gfn, level));
+	return rmap_head ? : &kvm_empty_rmap_head;
+}
+
+static struct kvm_rmap_head *gfn_to_rmap_alloc(struct kvm *kvm,
+					       struct kvm_mmu_memory_cache *cache,
+					       gfn_t gfn, int level,
+					       const struct kvm_memory_slot *slot)
+{
+	unsigned long idx = gfn_to_index(gfn, slot->base_gfn, level);
+	struct kvm_rmap_head **chunkp, *chunk;
+
+	lockdep_assert_held_write(&kvm->mmu_lock);
+
+	chunkp = rmap_chunkp(slot, level, idx);
+	chunk = *chunkp;
+	if (!chunk) {
+		chunk = kvm_mmu_memory_cache_alloc(cache);
+		/* Publish the zeroed chunk to lockless walkers. */
+		smp_store_release(chunkp, chunk);
+	}
+
+	return &chunk[idx % KVM_RMAP_CHUNK_NR_HEADS];
 }
 
 static void rmap_remove(struct kvm *kvm, u64 *spte)
@@ -1577,17 +1641,21 @@ struct slot_rmap_walk_iterator {
 	struct kvm_rmap_head *rmap;
 	int level;
 
-	/* private field. */
-	struct kvm_rmap_head *end_rmap;
+	/* private fields. */
+	unsigned long idx;
+	unsigned long end_idx;
 };
 
 static void rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator,
 				 int level)
 {
+	const struct kvm_memory_slot *slot = iterator->slot;
+
 	iterator->level = level;
 	iterator->gfn = iterator->start_gfn;
-	iterator->rmap = gfn_to_rmap(iterator->gfn, level, iterator->slot);
-	iterator->end_rmap = gfn_to_rmap(iterator->end_gfn, level, iterator->slot);
+	iterator->idx = gfn_to_index(iterator->start_gfn, slot->base_gfn, level);
+	iterator->end_idx = gfn_to_index(iterator->end_gfn, slot->base_gfn, level);
+	iterator->rmap = gfn_to_rmap(iterator->gfn, level, slot);
 }
 
 static void slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
@@ -1611,11 +1679,27 @@ static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
 
 static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
 {
-	while (++iterator->rmap <= iterator->end_rmap) {
+	struct kvm_rmap_head *rmap_head;
+	unsigned long skip;
+
+	while (++iterator->idx <= iterator->end_idx) {
 		iterator->gfn += KVM_PAGES_PER_HPAGE(iterator->level);
 
-		if (atomic_long_read(&iterator->rmap->val))
+		rmap_head = __idx_to_rmap(iterator->slot, iterator->level,
+					  iterator->idx);
+		if (!rmap_head) {
+			/* Skip the rest of the unallocated chunk. */
+			skip = KVM_RMAP_CHUNK_NR_HEADS - 1 -
+			       iterator->idx % KVM_RMAP_CHUNK_NR_HEADS;
+			iterator->idx += skip;
+			iterator->gfn += skip * KVM_PAGES_PER_HPAGE(iterator->level);
+			continue;
+		}
+
+		if (atomic_long_read(&rmap_head->val)) {
+			iterator->rmap = rmap_head;
 			return;
+		}
 	}
 
 	if (++iterator->level > iterator->end_level) {
@@ -1734,6 +1818,7 @@ bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
 
 static void __rmap_add(struct kvm *kvm,
 		       struct kvm_mmu_memory_cache *cache,
+		       struct kvm_mmu_memory_cache *chunk_cache,
 		       const struct kvm_memory_slot *slot,
 		       u64 *spte, gfn_t gfn, unsigned int access)
 {
@@ -1745,7 +1830,7 @@ static void __rmap_add(struct kvm *kvm,
 	kvm_mmu_page_set_translation(sp, spte_index(spte), gfn, access);
 	kvm_update_page_stats(kvm, sp->role.level, 1);
 
-	rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
+	rmap_head = gfn_to_rmap_alloc(kvm, chunk_cache, gfn, sp->role.level, slot);
 	rmap_count = pte_list_add(kvm, cache, spte, rmap_head);
 
 	if (rmap_count > kvm->stat.max_mmu_rmap_size)
@@ -1759,9 +1844,8 @@ static void __rmap_add(struct kvm *kvm,
 static void rmap_add(struct kvm_vcpu *vcpu, const struct kvm_memory_slot *slot,
 		     u64 *spte, gfn_t gfn, unsigned int access)
 {
-	struct kvm_mmu_memory_cache *cache = &vcpu->arch.mmu_pte_list_desc_cache;
-
-	__rmap_add(vcpu->kvm, cache, slot, spte, gfn, access);
+	__rmap_add(vcpu->kvm, &vcpu->arch.mmu_pte_list_desc_cache,
+		   &vcpu->arch.mmu_rmap_chunk_cache, slot, spte, gfn, access);
 }
 
 static bool kvm_rmap_age_gfn_range(struct kvm *kvm,
@@ -6963,6 +7047,8 @@ int kvm_mmu_create(struct kvm_vcpu *vcpu)
 	vcpu->arch.mmu_pte_list_desc_cache.kmem_cache = pte_list_desc_cache;
 	vcpu->arch.mmu_pte_list_desc_cache.gfp_zero = __GFP_ZERO;
 
+	vcpu->arch.mmu_rmap_chunk_cache.gfp_zero = __GFP_ZERO;
+
 	vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
 	vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
 
@@ -7150,12 +7236,15 @@ int kvm_mmu_init_vm(struct kvm *kvm)
 
 	kvm->arch.split_desc_cache.kmem_cache = pte_list_desc_cache;
 	kvm->arch.split_desc_cache.gfp_zero = __GFP_ZERO;
+
+	kvm->arch.split_rmap_chunk_cache.gfp_zero = __GFP_ZERO;
 	return 0;
 }
 
 static void mmu_free_vm_memory_caches(struct kvm *kvm)
 {
 	kvm_mmu_free_memory_cache(&kvm->arch.split_desc_cache);
+	kvm_mmu_free_memory_cache(&kvm->arch.split_rmap_chunk_cache);
 	kvm_mmu_free_memory_cache(&kvm->arch.split_page_header_cache);
 	kvm_mmu_free_memory_cache(&kvm->arch.split_shadow_page_cache);
 }
@@ -7274,6 +7363,8 @@ static bool need_topup_split_caches_or_resched(struct kvm *kvm)
 	 * is possible but not worth the complexity.
 	 */
 	return need_topup(&kvm->arch.split_desc_cache, SPLIT_DESC_CACHE_MIN_NR_OBJECTS) ||
+	       need_topup(&kvm->arch.split_rmap_chunk_cache,
+			  SPLIT_RMAP_CHUNK_CACHE_NR_OBJECTS) ||
 	       need_topup(&kvm->arch.split_page_header_cache, 1) ||
 	       need_topup(&kvm->arch.split_shadow_page_cache, 1);
 }
@@ -7304,6 +7395,12 @@ static int topup_split_caches(struct kvm *kvm)
 	if (r)
 		return r;
 
+	r = __kvm_mmu_topup_memory_cache(&kvm->arch.split_rmap_chunk_cache,
+					 SPLIT_RMAP_CHUNK_CACHE_NR_OBJECTS,
+					 SPLIT_RMAP_CHUNK_CACHE_NR_OBJECTS);
+	if (r)
+		return r;
+
 	r = kvm_mmu_topup_memory_cache(&kvm->arch.split_page_header_cache, 1);
 	if (r)
 		return r;
@@ -7378,7 +7475,8 @@ static void shadow_mmu_split_huge_page(struct kvm *kvm,
 
 		spte = make_small_spte(kvm, huge_spte, sp->role, index);
 		mmu_spte_set(sptep, spte);
-		__rmap_add(kvm, cache, slot, sptep, gfn, sp->role.access);
+		__rmap_add(kvm, cache, &kvm->arch.split_rmap_chunk_cache, slot,
+			   sptep, gfn, sp->role.access);
 	}
 
 	__link_shadow_page(kvm, cache, huge_sptep, sp, flush);
diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c
index 26e7beaff8a03c..6231c9649c95c6 100644
--- a/arch/x86/kvm/x86.c
+++ b/arch/x86/kvm/x86.c
@@ -10141,12 +10141,27 @@ void kvm_arch_destroy_vm(struct kvm *kvm)
 	kvm_x86_call(vm_destroy)(kvm);
 }
 
+static unsigned long memslot_rmap_nr_chunks(struct kvm_memory_slot *slot,
+					    unsigned long npages, int level)
+{
+	return DIV_ROUND_UP(__kvm_mmu_slot_lpages(slot, npages, level),
+			    KVM_RMAP_CHUNK_NR_HEADS);
+}
+
 static void memslot_rmap_free(struct kvm_memory_slot *slot)
 {
+	unsigned long j, nr_chunks;
 	int i;
 
 	for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
-		vfree(slot->arch.rmap[i]);
+		if (!slot->arch.rmap[i])
+			continue;
+
+		nr_chunks = memslot_rmap_nr_chunks(slot, slot->npages, i + 1);
+		for (j = 0; j < nr_chunks; j++)
+			free_page((unsigned long)slot->arch.rmap[i][j]);
+
+		kvfree(slot->arch.rmap[i]);
 		slot->arch.rmap[i] = NULL;
 	}
 }
@@ -10171,13 +10186,12 @@ int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)
 	int i;
 
 	for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
-		int level = i + 1;
-		int lpages = __kvm_mmu_slot_lpages(slot, npages, level);
+		unsigned long nr_chunks = memslot_rmap_nr_chunks(slot, npages, i + 1);
 
 		if (slot->arch.rmap[i])
 			continue;
 
-		slot->arch.rmap[i] = __vcalloc(lpages, sz, GFP_KERNEL_ACCOUNT);
+		slot->arch.rmap[i] = kvcalloc(nr_chunks, sz, GFP_KERNEL_ACCOUNT);
 		if (!slot->arch.rmap[i]) {
 			memslot_rmap_free(slot);
 			return -ENOMEM;
diff --git a/tools/testing/selftests/kvm/Makefile.kvm b/tools/testing/selftests/kvm/Makefile.kvm
index 17a4256e908191..61d88e0dd0ca8c 100644
--- a/tools/testing/selftests/kvm/Makefile.kvm
+++ b/tools/testing/selftests/kvm/Makefile.kvm
@@ -99,6 +99,7 @@ TEST_GEN_PROGS_x86 += x86/monitor_mwait_test
 TEST_GEN_PROGS_x86 += x86/msrs_test
 TEST_GEN_PROGS_x86 += x86/nested_close_kvm_test
 TEST_GEN_PROGS_x86 += x86/nested_dirty_log_test
+TEST_GEN_PROGS_x86 += x86/nested_dirty_log_sparse_test
 TEST_GEN_PROGS_x86 += x86/nested_emulation_test
 TEST_GEN_PROGS_x86 += x86/nested_exceptions_test
 TEST_GEN_PROGS_x86 += x86/nested_invalid_cr3_test
diff --git a/tools/testing/selftests/kvm/include/x86/processor.h b/tools/testing/selftests/kvm/include/x86/processor.h
index 5898a277a2e01c..66293e448ab2b4 100644
--- a/tools/testing/selftests/kvm/include/x86/processor.h
+++ b/tools/testing/selftests/kvm/include/x86/processor.h
@@ -1613,6 +1613,7 @@ void virt_map_level(struct kvm_vm *vm, gva_t gva, gpa_t gpa,
 
 void vm_enable_tdp(struct kvm_vm *vm);
 bool kvm_cpu_has_tdp(void);
+void __tdp_map(struct kvm_vm *vm, gpa_t l2_gpa, gpa_t gpa, u64 size, int level);
 void tdp_map(struct kvm_vm *vm, gpa_t l2_gpa, gpa_t gpa, u64 size);
 void tdp_identity_map_default_memslots(struct kvm_vm *vm);
 void tdp_identity_map_1g(struct kvm_vm *vm,  u64 addr, u64 size);
diff --git a/tools/testing/selftests/kvm/x86/nested_dirty_log_sparse_test.c b/tools/testing/selftests/kvm/x86/nested_dirty_log_sparse_test.c
new file mode 100644
index 00000000000000..bc1c6b8760c96e
--- /dev/null
+++ b/tools/testing/selftests/kvm/x86/nested_dirty_log_sparse_test.c
@@ -0,0 +1,275 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Dirty logging of memory that L2 maps sparsely.
+ *
+ * KVM allocates shadow MMU rmaps in chunks that cover 2 MiB of guest memory
+ * at the 4 KiB level, and only for chunks that hold a mapped gfn.  L2 writes
+ * pages at both ends of a chunk, in the next chunk, and in chunks separated
+ * by unallocated ones.  Enabling dirty logging write-protects the memslot by
+ * walking its rmaps, so a mapped page that the walk misses stays writable,
+ * and L2's next write to it is missing from the dirty log.
+ *
+ * A second test maps the memory with 2 MiB pages in L1's TDP page tables and
+ * verifies that eager page splitting splits the nested huge pages when
+ * dirty logging is enabled, and that the 4 KiB SPTEs it creates are logged.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <linux/bitmap.h>
+#include <linux/bitops.h>
+#include <linux/sizes.h>
+
+#include "test_util.h"
+#include "kvm_util.h"
+#include "processor.h"
+#include "svm_util.h"
+#include "vmx.h"
+
+#define TEST_MEM_SLOT		1
+#define TEST_MEM_BASE		0xc0000000ULL
+
+/* 64 MiB, i.e. 32 rmap chunks at the 4 KiB level. */
+#define SPARSE_MEM_PAGES	(SZ_64M / PAGE_SIZE)
+
+/* 4 huge pages for the eager page splitting test. */
+#define HUGE_MEM_PAGES		(4 * SZ_2M / PAGE_SIZE)
+#define HUGE_PAGES_PER_2M	(SZ_2M / PAGE_SIZE)
+
+/*
+ * Page indices L2 writes in the sparse test: both ends of the first two
+ * chunks, both ends of a chunk surrounded by unallocated chunks, and the
+ * last page of the memslot.
+ */
+static const u64 sparse_pages[] = { 0, 511, 512, 1023, 8192, 8703,
+				     SPARSE_MEM_PAGES - 1 };
+
+#define NR_SPARSE_PAGES		ARRAY_SIZE(sparse_pages)
+
+enum test_stage {
+	STAGE_POPULATE = 1,	/* L2 maps the pages, dirty logging is off */
+	STAGE_ALL,		/* L2 rewrites every page */
+	STAGE_SUBSET,		/* L2 rewrites every other page */
+};
+
+static bool huge_test;
+
+static void l2_write(u64 page, u64 val)
+{
+	WRITE_ONCE(*(u64 *)(TEST_MEM_BASE + page * PAGE_SIZE), val);
+}
+
+static u64 nr_test_pages(void)
+{
+	return huge_test ? HUGE_MEM_PAGES / HUGE_PAGES_PER_2M : NR_SPARSE_PAGES;
+}
+
+/* One page in each huge page in the huge test, the sparse pages otherwise. */
+static u64 test_page(u64 i)
+{
+	return huge_test ? i * HUGE_PAGES_PER_2M + 1 : sparse_pages[i];
+}
+
+static void l2_guest_code(void)
+{
+	u64 i;
+
+	for (i = 0; i < nr_test_pages(); i++)
+		l2_write(test_page(i), STAGE_POPULATE);
+	GUEST_SYNC(STAGE_POPULATE);
+
+	for (i = 0; i < nr_test_pages(); i++)
+		l2_write(test_page(i), STAGE_ALL);
+	GUEST_SYNC(STAGE_ALL);
+
+	for (i = 0; i < nr_test_pages(); i += 2)
+		l2_write(test_page(i), STAGE_SUBSET);
+	GUEST_SYNC(STAGE_SUBSET);
+
+	vmcall();
+}
+
+static void l1_vmx_code(struct vmx_pages *vmx)
+{
+	prepare_for_vmx_operation(vmx);
+	load_vmcs(vmx);
+	prepare_vmcs(vmx, l2_guest_code);
+
+	vmlaunch();
+	GUEST_ASSERT_EQ(vmread(VM_EXIT_REASON), EXIT_REASON_VMCALL);
+	GUEST_DONE();
+}
+
+static void l1_svm_code(struct svm_test_data *svm)
+{
+	generic_svm_setup(svm, l2_guest_code);
+
+	run_guest(svm->vmcb, svm->vmcb_gpa);
+	GUEST_ASSERT_EQ(svm->vmcb->control.exit_code, SVM_EXIT_VMMCALL);
+	GUEST_DONE();
+}
+
+static void l1_guest_code(void *data)
+{
+	if (this_cpu_has(X86_FEATURE_VMX))
+		l1_vmx_code(data);
+	else
+		l1_svm_code(data);
+}
+
+/* Returns true if L2 wrote @page in @stage. */
+static bool page_written(u64 page, enum test_stage stage)
+{
+	u64 i;
+
+	for (i = 0; i < nr_test_pages(); i++)
+		if (test_page(i) == page)
+			return stage != STAGE_SUBSET || !(i % 2);
+
+	return false;
+}
+
+static void check_dirty_log(struct kvm_vm *vm, u64 npages,
+			    enum test_stage stage, unsigned long *bmap)
+{
+	u64 page;
+
+	kvm_vm_get_dirty_log(vm, TEST_MEM_SLOT, bmap);
+
+	for (page = 0; page < npages; page++) {
+		bool written = page_written(page, stage);
+
+		TEST_ASSERT(test_bit(page, bmap) == written,
+			    "Stage %d: page %lu incorrectly reported %s",
+			    stage, page, written ? "clean" : "dirty");
+		if (written)
+			TEST_ASSERT_EQ(*(u64 *)addr_gpa2hva(vm, TEST_MEM_BASE + page * PAGE_SIZE),
+				       stage);
+	}
+}
+
+static void test_dirty_log(bool nested_tdp, bool huge)
+{
+	u64 npages = huge ? HUGE_MEM_PAGES : SPARSE_MEM_PAGES;
+	enum vm_mem_backing_src_type src;
+	u64 pages_2m = 0, pages_4k = 0;
+	gva_t nested_gva = 0;
+	struct kvm_vcpu *vcpu;
+	unsigned long *bmap;
+	struct kvm_vm *vm;
+	struct ucall uc;
+
+	pr_info("Nested TDP: %s, L1 TDP page size: %s\n",
+		nested_tdp ? "enabled" : "disabled", huge ? "2M" : "4K");
+
+	/* Room for L1's page tables and TDP page tables of the test memory. */
+	vm = __vm_create_with_one_vcpu(&vcpu, 2 * (npages / 512 + 16),
+				       l1_guest_code);
+	if (nested_tdp)
+		vm_enable_tdp(vm);
+
+	if (kvm_cpu_has(X86_FEATURE_VMX))
+		vcpu_alloc_vmx(vm, &nested_gva);
+	else
+		vcpu_alloc_svm(vm, &nested_gva);
+	vcpu_args_set(vcpu, 1, nested_gva);
+
+	src = huge ? VM_MEM_SRC_ANONYMOUS_HUGETLB : VM_MEM_SRC_ANONYMOUS;
+	vm_userspace_mem_region_add(vm, src, TEST_MEM_BASE, TEST_MEM_SLOT,
+				    npages, 0);
+	virt_map(vm, TEST_MEM_BASE, TEST_MEM_BASE, npages);
+
+	if (nested_tdp) {
+		tdp_identity_map_default_memslots(vm);
+		__tdp_map(vm, TEST_MEM_BASE, TEST_MEM_BASE, npages * PAGE_SIZE,
+			  huge ? PG_LEVEL_2M : PG_LEVEL_4K);
+	}
+
+	huge_test = huge;
+	sync_global_to_guest(vm, huge_test);
+
+	bmap = bitmap_zalloc(npages);
+
+	for (;;) {
+		vcpu_run(vcpu);
+		TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO);
+
+		switch (get_ucall(vcpu, &uc)) {
+		case UCALL_ABORT:
+			REPORT_GUEST_ASSERT(uc);
+			/* NOT REACHED */
+		case UCALL_SYNC:
+			break;
+		case UCALL_DONE:
+			goto done;
+		default:
+			TEST_FAIL("Unknown ucall %lu", uc.cmd);
+		}
+
+		if (uc.args[1] != STAGE_POPULATE) {
+			check_dirty_log(vm, npages, uc.args[1], bmap);
+			continue;
+		}
+
+		if (huge) {
+			pages_2m = vm_get_stat(vm, pages_2m);
+			pages_4k = vm_get_stat(vm, pages_4k);
+		}
+
+		/* Write-protect the memslot by walking its rmaps. */
+		vm_mem_region_set_flags(vm, TEST_MEM_SLOT, KVM_MEM_LOG_DIRTY_PAGES);
+
+		/*
+		 * Only L2 maps the test memslot, so eager page splitting must
+		 * have split exactly the nested huge pages L2 populated.
+		 */
+		if (huge) {
+			u64 nr_huge = npages / HUGE_PAGES_PER_2M;
+			u64 split = pages_2m - vm_get_stat(vm, pages_2m);
+
+			TEST_ASSERT(split == nr_huge,
+				    "Split %lu nested 2M pages, expected %lu",
+				    split, nr_huge);
+			TEST_ASSERT_EQ(vm_get_stat(vm, pages_4k),
+				       pages_4k + nr_huge * HUGE_PAGES_PER_2M);
+		}
+	}
+
+done:
+	free(bmap);
+	kvm_vm_free(vm);
+}
+
+static u64 free_2m_hugepages(void)
+{
+	u64 nr = 0;
+	FILE *f;
+
+	f = fopen("/sys/kernel/mm/hugepages/hugepages-2048kB/free_hugepages", "r");
+	if (!f)
+		return 0;
+	if (fscanf(f, "%lu", &nr) != 1)
+		nr = 0;
+	fclose(f);
+
+	return nr;
+}
+
+int main(int argc, char *argv[])
+{
+	TEST_REQUIRE(kvm_cpu_has(X86_FEATURE_VMX) || kvm_cpu_has(X86_FEATURE_SVM));
+
+	test_dirty_log(/*nested_tdp=*/false, /*huge=*/false);
+
+	if (!kvm_cpu_has_tdp())
+		return 0;
+
+	test_dirty_log(/*nested_tdp=*/true, /*huge=*/false);
+
+	if (free_2m_hugepages() >= HUGE_MEM_PAGES / HUGE_PAGES_PER_2M &&
+	    get_kvm_param_bool("tdp_mmu") && get_kvm_param_bool("eager_page_split"))
+		test_dirty_log(/*nested_tdp=*/true, /*huge=*/true);
+	else
+		pr_info("Skipping eager page splitting test, needs 4 free 2M hugepages, tdp_mmu and eager_page_split\n");
+
+	return 0;
+}

47/3 2026/11/06 06:54 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 12370
							output: 49
							thoughts: 632
						

Thoughts:
**KMSAN Fuzzing for x86 MMU Rmap Handling Patch: A Critical Evaluation**

Okay, let's break this down. My initial thought is to determine if this patch to KVM's x86 MMU rmap handling warrants a dedicated KMSAN fuzzing session. It's a significant change, so a thorough review is crucial.

First, I need to understand what's changed. Previously, the `struct kvm_arch_memory_slot` held a contiguous, flat array of `struct kvm_rmap_head` for each memory slot. It seems like the old method used `__vcalloc` to pre-allocate this entire array upfront. The patch introduces a more granular approach using "chunks." Now, the `rmap` array is a pointer to an array of pointers to `struct kvm_rmap_head`. These are essentially per-level directories of rmap chunks. Each chunk holds a fixed number of rmap heads, calculated based on page size.

Crucially, the chunks are allocated *on-demand*. They're allocated only when the KVM kernel adds the first SPTE (Shadow Page Table Entry) to a head within that chunk's range. A NULL chunk signals that it's unallocated, and the function `gfn_to_rmap` returns a `kvm_empty_rmap_head`. Chunk allocation is handled by `gfn_to_rmap_alloc()` using `kvm_mmu_memory_cache_alloc` from a memory cache that uses `__GFP_ZERO`. The code stores the chunk using `smp_store_release`, which is good to see. The patch uses `kvcalloc` for the chunk array allocation.

Now, here's where my alarm bells start ringing. I need to be *absolutely* certain about the memory management. In the chunk freeing section, `memslot_rmap_free()` is responsible for deallocating the chunks. The code uses `free_page((unsigned long)slot->arch.rmap[i][j])` to free each chunk. But, where is the chunk allocated?

I need to confirm if these chunks are allocated with `get_zeroed_page`, because I see the memory cache uses `__GFP_ZERO`. To be confident, I will use `grepper` and search for the function `kvm_mmu_memory_cache_alloc` to check what kind of memory is being allocated. I need to know exactly how those chunks are being allocated and freed. Is `free_page` the correct function for this chunk deallocation? This chunk allocation and deallocation code could introduce a KMSAN vulnerability. Given that the `kvm_mmu_memory_cache_alloc` memory cache uses `__GFP_ZERO`, these chunks appear to be allocated from a page of zeroed memory, which means that `free_page` is the correct function.

Once I have verified these allocations and deallocations, I can start to develop a plan to fuzz the changes.



48/3 2026/11/06 06:55 tool grepper
0m Args:
{
  "Expression": "kvm_mmu_memory_cache_alloc",
  "PathPrefixes": [
    "arch/x86/kvm/",
    "virt/kvm/"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/mmu/mmu.c=1083=static int pte_list_add(struct kvm *kvm, struct kvm_mmu_memory_cache *cache,\n--\narch/x86/kvm/mmu/mmu.c-1094-\t} else if (!(old_val \u0026 KVM_RMAP_MANY)) {\narch/x86/kvm/mmu/mmu.c:1095:\t\tdesc = kvm_mmu_memory_cache_alloc(cache);\narch/x86/kvm/mmu/mmu.c-1096-\t\tdesc-\u003esptes[0] = (u64 *)old_val;\n--\narch/x86/kvm/mmu/mmu.c-1110-\t\tif (desc-\u003espte_count == PTE_LIST_EXT) {\narch/x86/kvm/mmu/mmu.c:1111:\t\t\tdesc = kvm_mmu_memory_cache_alloc(cache);\narch/x86/kvm/mmu/mmu.c-1112-\t\t\tdesc-\u003emore = (struct pte_list_desc *)(old_val \u0026 ~KVM_RMAP_MANY);\n--\narch/x86/kvm/mmu/mmu.c=1291=static struct kvm_rmap_head *gfn_to_rmap_alloc(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-1303-\tif (!chunk) {\narch/x86/kvm/mmu/mmu.c:1304:\t\tchunk = kvm_mmu_memory_cache_alloc(cache);\narch/x86/kvm/mmu/mmu.c-1305-\t\t/* Publish the zeroed chunk to lockless walkers. */\n--\narch/x86/kvm/mmu/mmu.c=2504=static struct kvm_mmu_page *kvm_mmu_alloc_shadow_page(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-2511-\narch/x86/kvm/mmu/mmu.c:2512:\tsp = kvm_mmu_memory_cache_alloc(caches-\u003epage_header_cache);\narch/x86/kvm/mmu/mmu.c:2513:\tsp-\u003espt = kvm_mmu_memory_cache_alloc(caches-\u003eshadow_page_cache);\narch/x86/kvm/mmu/mmu.c-2514-\tif (!role.direct \u0026\u0026 role.level \u003c= KVM_MAX_HUGEPAGE_LEVEL)\narch/x86/kvm/mmu/mmu.c:2515:\t\tsp-\u003eshadowed_translation = kvm_mmu_memory_cache_alloc(caches-\u003eshadowed_info_cache);\narch/x86/kvm/mmu/mmu.c-2516-\n--\narch/x86/kvm/mmu/mmu_internal.h=160=static inline void kvm_mmu_alloc_external_spt(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)\n--\narch/x86/kvm/mmu/mmu_internal.h-167-\t */\narch/x86/kvm/mmu/mmu_internal.h:168:\tsp-\u003eexternal_spt = kvm_mmu_memory_cache_alloc(\u0026vcpu-\u003earch.mmu_external_spt_cache);\narch/x86/kvm/mmu/mmu_internal.h-169-}\n--\narch/x86/kvm/mmu/tdp_mmu.c=220=static struct kvm_mmu_page *tdp_mmu_alloc_sp(struct kvm_vcpu *vcpu)\n--\narch/x86/kvm/mmu/tdp_mmu.c-223-\narch/x86/kvm/mmu/tdp_mmu.c:224:\tsp = kvm_mmu_memory_cache_alloc(\u0026vcpu-\u003earch.mmu_page_header_cache);\narch/x86/kvm/mmu/tdp_mmu.c:225:\tsp-\u003espt = kvm_mmu_memory_cache_alloc(\u0026vcpu-\u003earch.mmu_shadow_page_cache);\narch/x86/kvm/mmu/tdp_mmu.c-226-\n--\nvirt/kvm/kvm_main.c=422=void kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)\n--\nvirt/kvm/kvm_main.c-436-\nvirt/kvm/kvm_main.c:437:void *kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)\nvirt/kvm/kvm_main.c-438-{\n"
}

49/3 2026/11/06 06:55 llm kmsan-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 14976
							output: 39
							thoughts: 31
						

Thoughts:
Okay, here's my take on those thoughts, framed as an expert's internal monologue:

**Investigating `kvm_mmu_memory_cache_alloc`**

Right, let's dive into this. I need to refresh my memory on the memory allocation strategy within KVM's MMU code. Specifically, I'm thinking about `kvm_mmu_memory_cache_alloc` in `virt/kvm/kvm_main.c`. Seems like a good place to start my investigation. I'm probably looking for a specific type of allocation, perhaps related to the caching of guest physical memory mappings. I'll need to understand the characteristics of that cache and how it's handled to see how it can be used for my needs. The function's name hints at a memory cache, so I'm expecting this to be important for performance. Let's see how they're handling allocation, sizing, and deallocation to get the full picture. My goal is to understand how well they've optimized the memory access path.



50/3 2026/11/06 06:56 tool read-file
0m Args:
{
  "File": "virt/kvm/kvm_main.c",
  "FirstLine": 420,
  "LineCount": 40
}

Results:
{
  "Contents": " 420:\t}\n 421:\t\n 422:\tvoid kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)\n 423:\t{\n 424:\t\twhile (mc-\u003enobjs) {\n 425:\t\t\tif (mc-\u003ekmem_cache)\n 426:\t\t\t\tkmem_cache_free(mc-\u003ekmem_cache, mc-\u003eobjects[--mc-\u003enobjs]);\n 427:\t\t\telse\n 428:\t\t\t\tfree_page((unsigned long)mc-\u003eobjects[--mc-\u003enobjs]);\n 429:\t\t}\n 430:\t\n 431:\t\tkvfree(mc-\u003eobjects);\n 432:\t\n 433:\t\tmc-\u003eobjects = NULL;\n 434:\t\tmc-\u003ecapacity = 0;\n 435:\t}\n 436:\t\n 437:\tvoid *kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)\n 438:\t{\n 439:\t\tvoid *p;\n 440:\t\n 441:\t\tif (WARN_ON(!mc-\u003enobjs))\n 442:\t\t\tp = mmu_memory_cache_alloc_obj(mc, GFP_ATOMIC | __GFP_ACCOUNT);\n 443:\t\telse\n 444:\t\t\tp = mc-\u003eobjects[--mc-\u003enobjs];\n 445:\t\tBUG_ON(!p);\n 446:\t\treturn p;\n 447:\t}\n 448:\t#endif\n 449:\t\n 450:\tstatic void kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)\n 451:\t{\n 452:\t\tmutex_init(\u0026vcpu-\u003emutex);\n 453:\t\tvcpu-\u003ecpu = -1;\n 454:\t\tvcpu-\u003ekvm = kvm;\n 455:\t\tvcpu-\u003evcpu_id = id;\n 456:\t\tvcpu-\u003epid = NULL;\n 457:\t\trwlock_init(\u0026vcpu-\u003epid_lock);\n 458:\t#ifndef __KVM_HAVE_ARCH_WQP\n 459:\t\trcuwait_init(\u0026vcpu-\u003ewait);\n"
}

51/3 2026/11/06 06:56 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 15876
							output: 39
							thoughts: 35
						

Thoughts:
Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:

**Diving into the KVM MMU Cache Allocation**

Alright, I'm going to take a deeper dive into the `mmu_memory_cache_alloc_obj` function and its interaction with the `kvm_mmu_memory_cache`. I need to get a clear understanding of how objects within that cache are being populated. I want to see precisely how memory is managed within the KVM MMU, and particularly, this `mmu_memory_cache_alloc_obj` function is key. I'm trying to visualize the lifecycle of these cache objects and any potential allocation or initialization strategies. I'm interested in the intricacies of its design. I need to refresh my understanding of object allocation and how it contributes to overall MMU performance, and any associated optimizations. Let's see how efficiently these objects are being managed.



52/3 2026/11/06 06:56 tool read-file
0m Args:
{
  "File": "virt/kvm/kvm_main.c",
  "FirstLine": 380,
  "LineCount": 45
}

Results:
{
  "Contents": " 380:\t\n 381:\t\tif (unlikely(!mc-\u003eobjects)) {\n 382:\t\t\tif (WARN_ON_ONCE(!capacity))\n 383:\t\t\t\treturn -EIO;\n 384:\t\n 385:\t\t\t/*\n 386:\t\t\t * Custom init values can be used only for page allocations,\n 387:\t\t\t * and obviously conflict with __GFP_ZERO.\n 388:\t\t\t */\n 389:\t\t\tif (WARN_ON_ONCE(mc-\u003einit_value \u0026\u0026 (mc-\u003ekmem_cache || mc-\u003egfp_zero)))\n 390:\t\t\t\treturn -EIO;\n 391:\t\n 392:\t\t\tmc-\u003eobjects = kvmalloc_array(capacity, sizeof(void *), gfp);\n 393:\t\t\tif (!mc-\u003eobjects)\n 394:\t\t\t\treturn -ENOMEM;\n 395:\t\n 396:\t\t\tmc-\u003ecapacity = capacity;\n 397:\t\t}\n 398:\t\n 399:\t\t/* It is illegal to request a different capacity across topups. */\n 400:\t\tif (WARN_ON_ONCE(mc-\u003ecapacity != capacity))\n 401:\t\t\treturn -EIO;\n 402:\t\n 403:\t\twhile (mc-\u003enobjs \u003c mc-\u003ecapacity) {\n 404:\t\t\tobj = mmu_memory_cache_alloc_obj(mc, gfp);\n 405:\t\t\tif (!obj)\n 406:\t\t\t\treturn mc-\u003enobjs \u003e= min ? 0 : -ENOMEM;\n 407:\t\t\tmc-\u003eobjects[mc-\u003enobjs++] = obj;\n 408:\t\t}\n 409:\t\treturn 0;\n 410:\t}\n 411:\t\n 412:\tint kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int min)\n 413:\t{\n 414:\t\treturn __kvm_mmu_topup_memory_cache(mc, KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE, min);\n 415:\t}\n 416:\t\n 417:\tint kvm_mmu_memory_cache_nr_free_objects(struct kvm_mmu_memory_cache *mc)\n 418:\t{\n 419:\t\treturn mc-\u003enobjs;\n 420:\t}\n 421:\t\n 422:\tvoid kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)\n 423:\t{\n 424:\t\twhile (mc-\u003enobjs) {\n"
}

53/3 2026/11/06 06:56 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 16845
							output: 39
							thoughts: 30
						

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

**Diving into KVM Memory Allocation**

Alright, time to dig into a potential memory allocation issue. I'm going to focus my attention on the `mmu_memory_cache_alloc_obj` function. My gut tells me this is the likely candidate for where things might be going sideways. I'll need to check how it's being used, what the typical call path looks like, and what resources it's managing within the virtualized environment. The specific file to inspect is `virt/kvm/kvm_main.c` – let's see what's happening within the KVM core. This is where I can get to the root of the problem and decide how to optimize the cache performance.



54/3 2026/11/06 06:56 tool read-file
0m Args:
{
  "File": "virt/kvm/kvm_main.c",
  "FirstLine": 345,
  "LineCount": 40
}

Results:
{
  "Contents": " 345:\t\t */\n 346:\t\tlockdep_assert_held(\u0026kvm-\u003eslots_lock);\n 347:\t\tkvm_flush_remote_tlbs_range(kvm, memslot-\u003ebase_gfn, memslot-\u003enpages);\n 348:\t}\n 349:\t\n 350:\tstatic void kvm_flush_shadow_all(struct kvm *kvm)\n 351:\t{\n 352:\t\tkvm_arch_flush_shadow_all(kvm);\n 353:\t\tkvm_arch_guest_memory_reclaimed(kvm);\n 354:\t}\n 355:\t\n 356:\t#ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE\n 357:\tstatic inline void *mmu_memory_cache_alloc_obj(struct kvm_mmu_memory_cache *mc,\n 358:\t\t\t\t\t\t       gfp_t gfp_flags)\n 359:\t{\n 360:\t\tvoid *page;\n 361:\t\n 362:\t\tgfp_flags |= mc-\u003egfp_zero;\n 363:\t\n 364:\t\tif (mc-\u003ekmem_cache)\n 365:\t\t\treturn kmem_cache_alloc(mc-\u003ekmem_cache, gfp_flags);\n 366:\t\n 367:\t\tpage = (void *)__get_free_page(gfp_flags);\n 368:\t\tif (page \u0026\u0026 mc-\u003einit_value)\n 369:\t\t\tmemset64(page, mc-\u003einit_value, PAGE_SIZE / sizeof(u64));\n 370:\t\treturn page;\n 371:\t}\n 372:\t\n 373:\tint __kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int capacity, int min)\n 374:\t{\n 375:\t\tgfp_t gfp = mc-\u003egfp_custom ? mc-\u003egfp_custom : GFP_KERNEL_ACCOUNT;\n 376:\t\tvoid *obj;\n 377:\t\n 378:\t\tif (mc-\u003enobjs \u003e= min)\n 379:\t\t\treturn 0;\n 380:\t\n 381:\t\tif (unlikely(!mc-\u003eobjects)) {\n 382:\t\t\tif (WARN_ON_ONCE(!capacity))\n 383:\t\t\t\treturn -EIO;\n 384:\t\n"
}

55/3 2026/11/06 06:56 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 17731
							output: 41
							thoughts: 442
						

Thoughts:
**Analyzing KVM's Memory Management for Potential Issues**

Okay, let's break down this memory allocation and freeing process, ensuring there are no hidden gotchas. My initial focus is on the `mmu_memory_cache_alloc_obj` function. I see it's setting the `gfp_flags` with `mc->gfp_zero`, and then applying this flag to allocate pages using `__get_free_page(gfp_flags)`. Crucially, it sets `mc->gfp_zero = __GFP_ZERO` for both `vcpu->arch.mmu_rmap_chunk_cache` and `kvm->arch.split_rmap_chunk_cache`. This confirms that each chunk is essentially a zero-filled page due to `__GFP_ZERO`. Perfect! Makes sense.

Now, on to the freeing mechanism. The code uses `free_page((unsigned long)slot->arch.rmap[i][j]);`. The natural concern here is what happens if a page isn't properly initialized – could we inadvertently call `free_page(0)`? Thankfully, I know `free_page(0)` is safe. Let's confirm:

Yup, it checks for a non-zero address before proceeding. So, we are safe. Great!

Next, I need to check how these rmaps are accessed elsewhere, specifically for any debugfs interactions or anything similar. Let's look at `arch/x86/kvm/debugfs.c`. In `kvm_mmu_rmaps_stat_level`, I see `unsigned int bucket = fls(pte_list_count(&chunk[index]));`. This is a little unclear at first. Also, `cur` is allocated on the stack.

I'm now checking the initialization of `log` within `kvm_mmu_rmaps_stat_show`, in the 90-130 section of `arch/x86/kvm/debugfs.c`, to check for off-by-one errors or anything similar.


56/3 2026/11/06 06:56 tool read-file
0m Args:
{
  "File": "arch/x86/kvm/debugfs.c",
  "FirstLine": 115,
  "LineCount": 45
}

Results:
{
  "Contents": " 115:\t\t}\n 116:\t}\n 117:\t\n 118:\tstatic int kvm_mmu_rmaps_stat_show(struct seq_file *m, void *v)\n 119:\t{\n 120:\t\tstruct kvm *kvm = m-\u003eprivate;\n 121:\t\tstruct kvm_memory_slot *slot;\n 122:\t\tstruct kvm_memslots *slots;\n 123:\t\t/* Still small enough to be on the stack */\n 124:\t\tunsigned int *log[KVM_NR_PAGE_SIZES], *cur;\n 125:\t\tint i, j, k, ret;\n 126:\t\n 127:\t\tif (!kvm_memslots_have_rmaps(kvm))\n 128:\t\t\treturn 0;\n 129:\t\n 130:\t\tret = -ENOMEM;\n 131:\t\tmemset(log, 0, sizeof(log));\n 132:\t\tfor (i = 0; i \u003c KVM_NR_PAGE_SIZES; i++) {\n 133:\t\t\tlog[i] = kcalloc(RMAP_LOG_SIZE, sizeof(unsigned int), GFP_KERNEL);\n 134:\t\t\tif (!log[i])\n 135:\t\t\t\tgoto out;\n 136:\t\t}\n 137:\t\n 138:\t\tmutex_lock(\u0026kvm-\u003eslots_lock);\n 139:\t\twrite_lock(\u0026kvm-\u003emmu_lock);\n 140:\t\n 141:\t\tfor (i = 0; i \u003c kvm_arch_nr_memslot_as_ids(kvm); i++) {\n 142:\t\t\tint bkt;\n 143:\t\n 144:\t\t\tslots = __kvm_memslots(kvm, i);\n 145:\t\t\tkvm_for_each_memslot(slot, bkt, slots)\n 146:\t\t\t\tfor (k = 0; k \u003c KVM_NR_PAGE_SIZES; k++)\n 147:\t\t\t\t\tkvm_mmu_rmaps_stat_level(slot, k + 1, log[k]);\n 148:\t\t}\n 149:\t\n 150:\t\twrite_unlock(\u0026kvm-\u003emmu_lock);\n 151:\t\tmutex_unlock(\u0026kvm-\u003eslots_lock);\n 152:\t\n 153:\t\t/* index=0 counts no rmap; index=1 counts 1 rmap */\n 154:\t\tseq_printf(m, \"Rmap_Count:\\t0\\t1\\t\");\n 155:\t\tfor (i = 2; i \u003c RMAP_LOG_SIZE; i++) {\n 156:\t\t\tj = 1 \u003c\u003c (i - 1);\n 157:\t\t\tk = (1 \u003c\u003c i) - 1;\n 158:\t\t\tseq_printf(m, \"%d-%d\\t\", j, k);\n 159:\t\t}\n"
}

57/3 2026/11/06 06:56 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 19433
							output: 36
							thoughts: 336
						

Thoughts:
**Checking for Uninitialized Data in KVM MMU RMAP Statistics**

Okay, I'm digging into this KVM MMU RMAP statistics code. First, I see `log[i] = kcalloc(RMAP_LOG_SIZE, sizeof(unsigned int), GFP_KERNEL);` – good, that's allocating and zeroing the memory, which is then printed out with `seq_printf`. No worries about uninitialized data there, `kcalloc` takes care of that.

Next, I'm looking at `kvm_mmu_rmaps_stat_level`. The code checks if a chunk is unallocated: `if (!chunk)`. If it is, then the counts are incremented directly.

Then there is this loop:

for (index = 0; index < nr; index++) {
    unsigned int bucket = fls(pte_list_count(&chunk[index]));

    if (WARN_ON_ONCE(bucket >= RMAP_LOG_SIZE))
        bucket = RMAP_LOG_SIZE - 1;
    cur[bucket]++;
}

This all seems perfectly safe. The loop accesses `chunk[index]` and the `bucket` is calculated based on the count. I am satisfied that all memory accessed here is properly initialized.

Okay, wait, let's take a closer look at `gfn_to_rmap` and `kvm_empty_rmap_head`. I need to ensure there are no subtle initialization issues hidden there. I see `static struct kvm_rmap_head kvm_empty_rmap_head;` - the `static` keyword means that the data will be zero-initialized during BSS. So when `rmap_head` is returned as `&kvm_empty_rmap_head`, I am sure the `val` field is 0 because `atomic_long_t val = 0`. I am happy with that.

Now, I'm going to track down who calls `gfn_to_rmap` and see what they're doing with the result, just to be absolutely certain there are no surprises downstream. I should verify that the zeroed `kvm_empty_rmap_head` is handled correctly.


58/3 2026/11/06 06:57 tool grepper
0m Args:
{
  "Expression": "gfn_to_rmap",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/mmu/mmu.c=1237=unsigned int pte_list_count(struct kvm_rmap_head *rmap_head)\n--\narch/x86/kvm/mmu/mmu.c-1251-/*\narch/x86/kvm/mmu/mmu.c:1252: * Returned by gfn_to_rmap() for heads in a chunk that hasn't been allocated.\narch/x86/kvm/mmu/mmu.c-1253- * Readers see an empty rmap, and only __rmap_add() writes to a head that may\n--\narch/x86/kvm/mmu/mmu.c=1265=static struct kvm_rmap_head *__idx_to_rmap(const struct kvm_memory_slot *slot,\n--\narch/x86/kvm/mmu/mmu.c-1271-\t * Lockless walkers can observe a chunk being installed.  Pairs with\narch/x86/kvm/mmu/mmu.c:1272:\t * the smp_store_release() in gfn_to_rmap_alloc().\narch/x86/kvm/mmu/mmu.c-1273-\t */\n--\narch/x86/kvm/mmu/mmu.c-1280-\narch/x86/kvm/mmu/mmu.c:1281:static struct kvm_rmap_head *gfn_to_rmap(gfn_t gfn, int level,\narch/x86/kvm/mmu/mmu.c-1282-\t\t\t\t\t const struct kvm_memory_slot *slot)\n--\narch/x86/kvm/mmu/mmu.c-1290-\narch/x86/kvm/mmu/mmu.c:1291:static struct kvm_rmap_head *gfn_to_rmap_alloc(struct kvm *kvm,\narch/x86/kvm/mmu/mmu.c-1292-\t\t\t\t\t       struct kvm_mmu_memory_cache *cache,\n--\narch/x86/kvm/mmu/mmu.c=1312=static void rmap_remove(struct kvm *kvm, u64 *spte)\n--\narch/x86/kvm/mmu/mmu.c-1330-\tslot = __gfn_to_memslot(slots, gfn);\narch/x86/kvm/mmu/mmu.c:1331:\trmap_head = gfn_to_rmap(gfn, sp-\u003erole.level, slot);\narch/x86/kvm/mmu/mmu.c-1332-\n--\narch/x86/kvm/mmu/mmu.c=1497=static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-1510-\twhile (mask) {\narch/x86/kvm/mmu/mmu.c:1511:\t\trmap_head = gfn_to_rmap(slot-\u003ebase_gfn + gfn_offset + __ffs(mask),\narch/x86/kvm/mmu/mmu.c-1512-\t\t\t\t\tPG_LEVEL_4K, slot);\n--\narch/x86/kvm/mmu/mmu.c=1520=static void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-1533-\twhile (mask) {\narch/x86/kvm/mmu/mmu.c:1534:\t\trmap_head = gfn_to_rmap(slot-\u003ebase_gfn + gfn_offset + __ffs(mask),\narch/x86/kvm/mmu/mmu.c-1535-\t\t\t\t\tPG_LEVEL_4K, slot);\n--\narch/x86/kvm/mmu/mmu.c=1595=bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-1604-\t\tfor (i = min_level; i \u003c= KVM_MAX_HUGEPAGE_LEVEL; ++i) {\narch/x86/kvm/mmu/mmu.c:1605:\t\t\trmap_head = gfn_to_rmap(gfn, i, slot);\narch/x86/kvm/mmu/mmu.c-1606-\t\t\twrite_protected |= rmap_write_protect(rmap_head, true);\n--\narch/x86/kvm/mmu/mmu.c=1649=static void rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator,\n--\narch/x86/kvm/mmu/mmu.c-1657-\titerator-\u003eend_idx = gfn_to_index(iterator-\u003eend_gfn, slot-\u003ebase_gfn, level);\narch/x86/kvm/mmu/mmu.c:1658:\titerator-\u003ermap = gfn_to_rmap(iterator-\u003egfn, level, slot);\narch/x86/kvm/mmu/mmu.c-1659-}\n--\narch/x86/kvm/mmu/mmu.c=1819=static void __rmap_add(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-1832-\narch/x86/kvm/mmu/mmu.c:1833:\trmap_head = gfn_to_rmap_alloc(kvm, chunk_cache, gfn, sp-\u003erole.level, slot);\narch/x86/kvm/mmu/mmu.c-1834-\trmap_count = pte_list_add(kvm, cache, spte, rmap_head);\n--\narch/x86/kvm/mmu/mmu.c=1851=static bool kvm_rmap_age_gfn_range(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-1879-\t\t     gfn += KVM_PAGES_PER_HPAGE(level)) {\narch/x86/kvm/mmu/mmu.c:1880:\t\t\trmap_head = gfn_to_rmap(gfn, level, range-\u003eslot);\narch/x86/kvm/mmu/mmu.c-1881-\t\t\trmap_val = kvm_rmap_lock_readonly(kvm, rmap_head);\n"
}

59/3 2026/11/06 06:57 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 22018
							output: 45
							thoughts: 534
						

Thoughts:
**Diving into the KVM Rmap Walk**

Okay, let's break down this rmap walk process. My initial focus is on `slot_rmap_walk_next`. I see it's an iterative function, incrementing an index and a GFN (Guest Frame Number). It's designed to traverse rmap heads within a memory slot. The `rmap_head` is fetched using `__idx_to_rmap`. The function carefully handles unallocated chunks by calculating a `skip` value to bypass them, based on `KVM_RMAP_CHUNK_NR_HEADS`. If an `rmap_head` exists and its atomic value (`rmap_head->val`) is non-zero, it signifies a valid rmap entry, and the function returns it. The iteration continues until either a valid rmap is found or the level is exhausted. If the level is exhausted it iterates through the levels using `rmap_walk_init_level`.

Now, digging deeper, I'm examining `rmap_walk_init_level`. This function is responsible for initializing the iterator for a specific level. It sets the current level, resets the GFN to the starting GFN, calculates the starting and ending indices using `gfn_to_index`, and attempts to obtain the `rmap` using `gfn_to_rmap`.

Hold on, I need to understand how the iterator is initialized. I need to see how `slot_rmap_walk_init` works. Since this is architecture-specific, I need to reference `arch/x86/kvm/mmu/mmu.c` to see how it's implemented in X86 KVM.



60/3 2026/11/06 06:57 tool read-file
0m Args:
{
  "File": "arch/x86/kvm/mmu/mmu.c",
  "FirstLine": 1660,
  "LineCount": 30
}

Results:
{
  "Contents": "1660:\t\n1661:\tstatic void slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,\n1662:\t\t\t\t\tconst struct kvm_memory_slot *slot,\n1663:\t\t\t\t\tint start_level, int end_level,\n1664:\t\t\t\t\tgfn_t start_gfn, gfn_t end_gfn)\n1665:\t{\n1666:\t\titerator-\u003eslot = slot;\n1667:\t\titerator-\u003estart_level = start_level;\n1668:\t\titerator-\u003eend_level = end_level;\n1669:\t\titerator-\u003estart_gfn = start_gfn;\n1670:\t\titerator-\u003eend_gfn = end_gfn;\n1671:\t\n1672:\t\trmap_walk_init_level(iterator, iterator-\u003estart_level);\n1673:\t}\n1674:\t\n1675:\tstatic bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)\n1676:\t{\n1677:\t\treturn !!iterator-\u003ermap;\n1678:\t}\n1679:\t\n1680:\tstatic void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)\n1681:\t{\n1682:\t\tstruct kvm_rmap_head *rmap_head;\n1683:\t\tunsigned long skip;\n1684:\t\n1685:\t\twhile (++iterator-\u003eidx \u003c= iterator-\u003eend_idx) {\n1686:\t\t\titerator-\u003egfn += KVM_PAGES_PER_HPAGE(iterator-\u003elevel);\n1687:\t\n1688:\t\t\trmap_head = __idx_to_rmap(iterator-\u003eslot, iterator-\u003elevel,\n1689:\t\t\t\t\t\t  iterator-\u003eidx);\n"
}

61/3 2026/11/06 06:57 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 23427
							output: 35
							thoughts: 24
						

Thoughts:
Okay, let's see. Here's my thought process:

**Diving into Iterator Loop Usage**

Hmm, I'm a bit fuzzy on exactly how that iterator loop is being used in this context. Time to refresh my memory. Let's dig into the implementation of `for_each_slot_rmap_range`. That should clarify things, specifically how the iterator is actually employed within that function. I need to understand how the iteration is structured and what data it's processing. That level of detail will illuminate the loop's true purpose here. Let's get to it.



62/3 2026/11/06 06:57 tool grepper
0m Args:
{
  "Expression": "slot_rmap_walk",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/mmu/mmu.c=1625=static bool kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,\n--\narch/x86/kvm/mmu/mmu.c-1630-\narch/x86/kvm/mmu/mmu.c:1631:struct slot_rmap_walk_iterator {\narch/x86/kvm/mmu/mmu.c-1632-\t/* input fields. */\n--\narch/x86/kvm/mmu/mmu.c-1648-\narch/x86/kvm/mmu/mmu.c:1649:static void rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator,\narch/x86/kvm/mmu/mmu.c-1650-\t\t\t\t int level)\n--\narch/x86/kvm/mmu/mmu.c-1660-\narch/x86/kvm/mmu/mmu.c:1661:static void slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,\narch/x86/kvm/mmu/mmu.c-1662-\t\t\t\tconst struct kvm_memory_slot *slot,\n--\narch/x86/kvm/mmu/mmu.c-1674-\narch/x86/kvm/mmu/mmu.c:1675:static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)\narch/x86/kvm/mmu/mmu.c-1676-{\n--\narch/x86/kvm/mmu/mmu.c-1679-\narch/x86/kvm/mmu/mmu.c:1680:static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)\narch/x86/kvm/mmu/mmu.c-1681-{\n--\narch/x86/kvm/mmu/mmu.c-1714-\t   _start_gfn, _end_gfn, _iter_)\t\t\t\t\\\narch/x86/kvm/mmu/mmu.c:1715:\tfor (slot_rmap_walk_init(_iter_, _slot_, _start_level_,\t\t\\\narch/x86/kvm/mmu/mmu.c-1716-\t\t\t\t _end_level_, _start_gfn, _end_gfn);\t\\\narch/x86/kvm/mmu/mmu.c:1717:\t     slot_rmap_walk_okay(_iter_);\t\t\t\t\\\narch/x86/kvm/mmu/mmu.c:1718:\t     slot_rmap_walk_next(_iter_))\narch/x86/kvm/mmu/mmu.c-1719-\n--\narch/x86/kvm/mmu/mmu.c=1725=static __always_inline bool __walk_slot_rmaps(struct kvm *kvm,\n--\narch/x86/kvm/mmu/mmu.c-1732-{\narch/x86/kvm/mmu/mmu.c:1733:\tstruct slot_rmap_walk_iterator iterator;\narch/x86/kvm/mmu/mmu.c-1734-\n"
}

63/3 2026/11/06 06:57 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 24502
							output: 45
							thoughts: 16
						

Thoughts:
Okay, let's dive into this. Here's my thought process as I approach understanding `__walk_slot_rmaps`:

**Deciphering `__walk_slot_rmaps`**

Alright, I'm encountering `__walk_slot_rmaps`. I immediately need to understand its purpose. "walk" suggests iteration, going through something. "slot" likely points to a specific data structure or location within a larger container. "rmaps"... that's the interesting part. "r" could stand for "reverse" or "related", but "map" definitely tells me this function deals with associating data in some way. So, this feels like an iterator or function designed to traverse and process something related to some kind of reverse-lookup map, possibly within specific "slots" of a larger structure. I need to get into the details to confirm the intuition here. I need to look at the surrounding context to confirm my initial hypothesis.



64/3 2026/11/06 06:57 tool read-file
0m Args:
{
  "File": "arch/x86/kvm/mmu/mmu.c",
  "FirstLine": 1725,
  "LineCount": 35
}

Results:
{
  "Contents": "1725:\tstatic __always_inline bool __walk_slot_rmaps(struct kvm *kvm,\n1726:\t\t\t\t\t\t      const struct kvm_memory_slot *slot,\n1727:\t\t\t\t\t\t      slot_rmaps_handler fn,\n1728:\t\t\t\t\t\t      int start_level, int end_level,\n1729:\t\t\t\t\t\t      gfn_t start_gfn, gfn_t end_gfn,\n1730:\t\t\t\t\t\t      bool can_yield, bool flush_on_yield,\n1731:\t\t\t\t\t\t      bool flush)\n1732:\t{\n1733:\t\tstruct slot_rmap_walk_iterator iterator;\n1734:\t\n1735:\t\tlockdep_assert_held_write(\u0026kvm-\u003emmu_lock);\n1736:\t\n1737:\t\tfor_each_slot_rmap_range(slot, start_level, end_level, start_gfn,\n1738:\t\t\t\tend_gfn, \u0026iterator) {\n1739:\t\t\tif (iterator.rmap)\n1740:\t\t\t\tflush |= fn(kvm, iterator.rmap, slot);\n1741:\t\n1742:\t\t\tif (!can_yield)\n1743:\t\t\t\tcontinue;\n1744:\t\n1745:\t\t\tif (need_resched() || rwlock_needbreak(\u0026kvm-\u003emmu_lock)) {\n1746:\t\t\t\tif (flush \u0026\u0026 flush_on_yield) {\n1747:\t\t\t\t\tkvm_flush_remote_tlbs_range(kvm, start_gfn,\n1748:\t\t\t\t\t\t\t\t    iterator.gfn - start_gfn + 1);\n1749:\t\t\t\t\tflush = false;\n1750:\t\t\t\t}\n1751:\t\t\t\tcond_resched_rwlock_write(\u0026kvm-\u003emmu_lock);\n1752:\t\t\t}\n1753:\t\t}\n1754:\t\n1755:\t\treturn flush;\n1756:\t}\n1757:\t\n1758:\tstatic __always_inline bool walk_slot_rmaps(struct kvm *kvm,\n1759:\t\t\t\t\t\t    const struct kvm_memory_slot *slot,\n"
}

65/3 2026/11/06 06:57 llm kmsan-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 25327
							output: 44
							thoughts: 2228
						

Thoughts:
**Analysis of `slot_rmap_walk_next` and KMSAN Applicability**

Okay, let's break this down. I'm looking closely at how `slot_rmap_walk_next` works, specifically focusing on the iterator and its interaction with the rmap structures. Initially, I was concerned about the scenario where `iterator.rmap` might be empty on the first entry. After following the initialization through `slot_rmap_walk_init` and `rmap_walk_init_level`, I see that `gfn_to_rmap` can return `&kvm_empty_rmap_head` if a chunk hasn't been allocated, which is key. This head's value being zero means `atomic_long_read` will return zero, but the code still proceeds. I was tracing how the old code and new code handles that, and how the handler checks are implemented. I had some initial concerns there.

However, after carefully examining the code and the context, I think there is no issue here. I see that the iteration handles the case where the rmap chunk isn't allocated correctly, and moves on if it encounters that chunk. The code gracefully skips over unallocated rmaps.

Now, the crucial question is whether this code introduces risks related to uninitialized memory. I need to make a solid call here, and that requires applying the KMSAN criteria.

My assessment is no, this is not a KMSAN issue. I've re-read the distinction between KASAN and KMSAN. KMSAN is for catching reads of truly uninitialized memory or for user-space info leaks. In my analysis, I am going to need to look specifically at the criteria for uninitialized memory risks.

First, I examined whether kernel structures are being sent to user space, checking what kind of output this has. It turns out that the user-facing output is `kvm_mmu_rmaps_stat_show` via debugfs, which prints integers from `log[k]`, which is `kcalloc`ed and `memset`ed. I see that the dirty logging is handled via other code. This is not sending potentially uninitialized memory to user space.

Second, are there potentially uninitialized variables or struct fields? The rmap structures (`slot->arch.rmap[i]`) are allocated using `kvcalloc`, which zero-initializes them. Chunk pages are also allocated with `__GFP_ZERO`. `kvm_empty_rmap_head` is zero initialized. The `log` array in `kvm_mmu_rmaps_stat_show` is allocated with `kcalloc` and is `memset`'d. In the iterator, all the fields get properly set. No uninitialized memory is read.

Third, what are the potential bugs with this code? Looking at it, it seems like we are at risk for off-by-one errors that can happen in indexes, array access errors, or potential concurrency issues. Freeing of the pages themselves, which is something that can be caught. These potential bugs should get caught by KASAN or standard bug detectors.

Therefore, none of the risks in the patch involve reading uninitialized memory. Everything is zero-initialized using `kvcalloc` or `__GFP_ZERO`. KMSAN would not provide added value here. KASAN and standard detectors would be fully equipped to catch all the errors that this patch could make.

I'm going to do a final check on `kvcalloc` and `free_page` just to be completely sure. I need to double-check that `sz` is passed correctly to `kvcalloc`. Let's confirm that by reviewing the `memslot_rmap_alloc` implementation in `arch/x86/kvm/x86.c`.



66/3 2026/11/06 06:59 tool read-file
0m Args:
{
  "File": "arch/x86/kvm/x86.c",
  "FirstLine": 10180,
  "LineCount": 25
}

Results:
{
  "Contents": "10180:\t\tkvm_page_track_free_memslot(slot);\n10181:\t}\n10182:\t\n10183:\tint memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)\n10184:\t{\n10185:\t\tconst int sz = sizeof(*slot-\u003earch.rmap[0]);\n10186:\t\tint i;\n10187:\t\n10188:\t\tfor (i = 0; i \u003c KVM_NR_PAGE_SIZES; ++i) {\n10189:\t\t\tunsigned long nr_chunks = memslot_rmap_nr_chunks(slot, npages, i + 1);\n10190:\t\n10191:\t\t\tif (slot-\u003earch.rmap[i])\n10192:\t\t\t\tcontinue;\n10193:\t\n10194:\t\t\tslot-\u003earch.rmap[i] = kvcalloc(nr_chunks, sz, GFP_KERNEL_ACCOUNT);\n10195:\t\t\tif (!slot-\u003earch.rmap[i]) {\n10196:\t\t\t\tmemslot_rmap_free(slot);\n10197:\t\t\t\treturn -ENOMEM;\n10198:\t\t\t}\n10199:\t\t}\n10200:\t\n10201:\t\treturn 0;\n10202:\t}\n10203:\t\n10204:\tstatic int kvm_alloc_memslot_metadata(struct kvm *kvm,\n"
}

67/3 2026/11/06 06:59 llm kmsan-evaluator
3m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 28811
							output: 345
							thoughts: 711
						

Thoughts:
**KMSAN Assessment: KVM Shadow MMU Rmap Allocation Refactor**

Okay, so I've been through this patch, which refactors the KVM shadow MMU rmap allocation strategy. My initial assessment is that this doesn't necessitate a dedicated KMSAN fuzzing session, and here's why.

First, let's break down what's happening. The patch moves from a single monolithic array to on-demand allocated chunks (pages of `struct kvm_rmap_head`). The critical question, as always in memory management, is initialization.

The code uses `kvcalloc()` to allocate the chunk directory pointers (`slot->arch.rmap[i]`). `kvcalloc()` is critical here; it zeroes the memory. Also, the individual rmap chunks are allocated via `kvm_mmu_memory_cache_alloc()` using caches which are configured to use `__GFP_ZERO`. Meaning these chunks are zeroed at allocation time. We have a static global zeroed `kvm_empty_rmap_head` as the empty fallback. And debugfs statistics buffers are allocated with `kcalloc()` which, again, provides zero initialization.

Now, where are the risks? The areas that concern me are the chunk boundary calculations, specifically in indexing, iterator traversal, chunk lifetime, and any potential locking issues. However, the good news is that these are all issues that are well-covered by existing kernel instrumentation. Any indexing errors or iterator issues would likely manifest as out-of-bounds accesses, and KASAN is there to catch that immediately. Memory management problems like use-after-free or double-free would trigger KASAN as well. LOCKDEP and KCSAN are there to catch locking and concurrency problems.

The code *explicitly* initializes everything that's introduced. This is critical. There's no uninitialized memory, which means no possibility of sensitive information leaking to userspace or being used for control flow in an unpredictable way.

So, in conclusion, the risks are all in areas already well-addressed by KASAN and standard kernel debuggers. There's no uninitialized memory. Therefore, NeedsKMSAN should be false. We can focus our efforts on standard fuzzing strategies. Now, let's prepare the call to the set-results tool.



68/3 2026/11/06 07:02 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch transitions KVM shadow MMU rmap tracking from monolithic arrays to on-demand allocated chunk pages (each holding KVM_RMAP_CHUNK_NR_HEADS rmap heads).\n\nAnalysis of memory initialization and user-facing data:\n1. The chunk directories (`slot-\u003earch.rmap[i]`) are allocated using `kvcalloc()`, which zeroes all chunk pointers.\n2. The rmap chunk pages are allocated via `kvm_mmu_memory_cache_alloc()` from `mmu_rmap_chunk_cache` and `split_rmap_chunk_cache`, both of which are explicitly configured with `gfp_zero = __GFP_ZERO`, ensuring that every newly allocated chunk is zero-filled.\n3. The fallback `kvm_empty_rmap_head` is declared as static storage and thus is zero-initialized.\n4. The rmaps stat debugfs handler allocates its counting buckets with `kcalloc()`.\n5. No uninitialized memory, struct fields, or padding are exposed or copied to user space.\n\nPotential bugs in this patch involve chunk indexing arithmetic, iterator walk logic, concurrent lockless chunk installation, or chunk deallocation (`free_page`), which could lead to out-of-bounds accesses, use-after-free, or synchronization errors. These risks are effectively detected by KASAN, LOCKDEP, and page debugging tools. Because there are no uninitialized memory access or info-leak risks, a dedicated KMSAN fuzzing session is not justified.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch transitions KVM shadow MMU rmap tracking from monolithic arrays to on-demand allocated chunk pages (each holding KVM_RMAP_CHUNK_NR_HEADS rmap heads).\n\nAnalysis of memory initialization and user-facing data:\n1. The chunk directories (`slot-\u003earch.rmap[i]`) are allocated using `kvcalloc()`, which zeroes all chunk pointers.\n2. The rmap chunk pages are allocated via `kvm_mmu_memory_cache_alloc()` from `mmu_rmap_chunk_cache` and `split_rmap_chunk_cache`, both of which are explicitly configured with `gfp_zero = __GFP_ZERO`, ensuring that every newly allocated chunk is zero-filled.\n3. The fallback `kvm_empty_rmap_head` is declared as static storage and thus is zero-initialized.\n4. The rmaps stat debugfs handler allocates its counting buckets with `kcalloc()`.\n5. No uninitialized memory, struct fields, or padding are exposed or copied to user space.\n\nPotential bugs in this patch involve chunk indexing arithmetic, iterator walk logic, concurrent lockless chunk installation, or chunk deallocation (`free_page`), which could lead to out-of-bounds accesses, use-after-free, or synchronization errors. These risks are effectively detected by KASAN, LOCKDEP, and page debugging tools. Because there are no uninitialized memory access or info-leak risks, a dedicated KMSAN fuzzing session is not justified.",
  "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)