AI Trajectory


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

Results:
{
  "EnableConfigs": [
    "TRANSPARENT_HUGEPAGE"
  ],
  "FocusSymbols": [
    "madvise_collapse",
    "collapse_single_pmd",
    "collapse_scan_pmd",
    "collapse_pmd",
    "collapse_anon",
    "collapse_scan_anon",
    "collapse_file",
    "collapse_scan_file",
    "khugepaged_do_scan"
  ],
  "KMSANReasoning": "The patch series refactors the transparent hugepage (THP) collapse logic in mm/khugepaged.c by introducing struct collapse_policy and struct collapse_control in mm/collapse.h to encapsulate collapse configurations (khugepaged vs madvise) and state across scan and collapse phases.\n\nEvaluating against KMSAN criteria:\n1. No kernel structures or data are copied to user space (no copy_to_user, put_user, netlink, ioctl output, socket options, or BPF buffers).\n2. All fields in struct collapse_policy and struct collapse_control are explicitly initialized (via collapse_control_init(), collapse_policy_khugepaged(), collapse_policy_madvise(), collapse_scan_reset(), and during successful scan phases) prior to being read or used in conditional logic.\n3. No uninitialized memory usage or info-leak risks are introduced. Any potential bugs in this refactoring would pertain to page/folio reference counting, locking (mmap_lock / folio locks), or state-tracking logic, which are covered by KASAN, LOCKDEP, and standard kernel debugging facilities.\n\nTherefore, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch refactors transparent huge page (THP) collapse logic in mm/khugepaged.c and introduces mm/collapse.h. It decouples scan and collapse phases into separate functions (collapse_scan_pmd, collapse_scan_anon, collapse_pmd, collapse_anon), formalizes collapse policies/limits between background khugepaged and MADV_COLLAPSE, alters file reference handling (with a new WARN_ON_ONCE assertion checking cc-\u003escan_file), and modifies reference management in madvise_collapse. This reachable core memory management code is actively exercised via madvise(MADV_COLLAPSE) and the khugepaged kthread.",
  "WorthFuzzing": true
}

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

Results:
{
  "PatchDiff": "commit ff94c96f8aca60d916dea20b7f431378dd8e74b0\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Wed Oct 14 23:14:02 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/MAINTAINERS b/MAINTAINERS\nindex 39abe7378b6fc..5c38da7090db8 100644\n--- a/MAINTAINERS\n+++ b/MAINTAINERS\n@@ -17452,6 +17452,7 @@ F:\tDocumentation/admin-guide/mm/transhuge.rst\n F:\tinclude/linux/huge_mm.h\n F:\tinclude/linux/khugepaged.h\n F:\tinclude/trace/events/huge_memory.h\n+F:\tmm/collapse.h\n F:\tmm/huge_memory.c\n F:\tmm/khugepaged.c\n F:\tmm/mm_slot.h\ndiff --git a/mm/collapse.h b/mm/collapse.h\nnew file mode 100644\nindex 0000000000000..759ec9cd45414\n--- /dev/null\n+++ b/mm/collapse.h\n@@ -0,0 +1,121 @@\n+/* SPDX-License-Identifier: GPL-2.0 */\n+#ifndef __MM_COLLAPSE_H\n+#define __MM_COLLAPSE_H\n+\n+#include \u003clinux/mm.h\u003e\n+#include \u003clinux/nodemask.h\u003e\n+#include \u003clinux/pgtable.h\u003e\n+#include \u003clinux/types.h\u003e\n+\n+#define COLLAPSE_MAX_PTES_LIMIT\t\t(HPAGE_PMD_NR - 1)\n+#define COLLAPSE_MIN_MTHP_ORDER\t\t2\n+\n+enum scan_result {\n+\tSCAN_FAIL,\n+\tSCAN_SUCCEED,\n+\tSCAN_NO_PTE_TABLE,\n+\tSCAN_PMD_MAPPED,\n+\tSCAN_EXCEED_NONE_PTE,\n+\tSCAN_EXCEED_SWAP_PTE,\n+\tSCAN_EXCEED_SHARED_PTE,\n+\tSCAN_PTE_NON_PRESENT,\n+\tSCAN_PTE_UFFD,\n+\tSCAN_PTE_MAPPED_HUGEPAGE,\n+\tSCAN_LACK_REFERENCED_PAGE,\n+\tSCAN_PAGE_NULL,\n+\tSCAN_SCAN_ABORT,\n+\tSCAN_PAGE_COUNT,\n+\tSCAN_PAGE_LRU,\n+\tSCAN_PAGE_LOCK,\n+\tSCAN_PAGE_ANON,\n+\tSCAN_PAGE_LAZYFREE,\n+\tSCAN_PAGE_COMPOUND,\n+\tSCAN_ANY_PROCESS,\n+\tSCAN_VMA_NULL,\n+\tSCAN_VMA_CHECK,\n+\tSCAN_ADDRESS_RANGE,\n+\tSCAN_DEL_PAGE_LRU,\n+\tSCAN_ALLOC_HUGE_PAGE_FAIL,\n+\tSCAN_CGROUP_CHARGE_FAIL,\n+\tSCAN_TRUNCATED,\n+\tSCAN_PAGE_HAS_PRIVATE,\n+\tSCAN_STORE_FAILED,\n+\tSCAN_COPY_MC,\n+\tSCAN_PAGE_FILLED,\n+\tSCAN_PAGE_DIRTY_OR_WRITEBACK,\n+};\n+\n+/* How many PTEs of a window may be missing, swapped out or shared */\n+struct collapse_limits {\n+\t/* Counted over a PMD-sized window; HPAGE_PMD_NR means \"no limit\" */\n+\tunsigned int max_ptes_none;\n+\tunsigned int max_ptes_swap;\n+\tunsigned int max_ptes_shared;\n+};\n+\n+/* What a collapse is allowed to do, decided by the caller that asks for it */\n+struct collapse_policy {\n+\t/* Limits for a PMD-sized window */\n+\tstruct collapse_limits pmd;\n+\n+\t/*\n+\t * Limits for a smaller window.  Its max_ptes_none is either 0 or\n+\t * COLLAPSE_MAX_PTES_LIMIT, the latter meaning all but one PTE of the\n+\t * window whatever its order; any other value counts as 0.\n+\t */\n+\tstruct collapse_limits sub_pmd;\n+\n+\t/* Leave clean lazyfree folios to reclaim rather than collapse them */\n+\tbool anon_skip_lazyfree;\n+\n+\t/* Refuse an anonymous range with no sign of use */\n+\tbool anon_require_referenced;\n+\n+\t/* Map the PMD over a file collapse instead of leaving it to a fault */\n+\tbool file_install_pmd;\n+\n+\t/* Write dirty pages back and retry once instead of refusing them */\n+\tbool file_writeback_dirty;\n+\n+\t/* How hard to try for a destination folio */\n+\tgfp_t gfp;\n+\n+\t/* Which VMAs are eligible, as thp_vma_allowable_orders() spells it */\n+\tenum tva_type tva_type;\n+};\n+\n+struct collapse_control {\n+\tstruct collapse_policy policy;\n+\n+\t/* Num pages scanned per node */\n+\tu32 node_load[MAX_NUMNODES];\n+\n+\t/* Num pages scanned (see khugepaged_pages_to_scan) */\n+\tunsigned int progress;\n+\n+\t/* nodemask for allocation fallback */\n+\tnodemask_t alloc_nmask;\n+\n+\t/* Each bit marks a PTE the scan accepted as a collapse source */\n+\tDECLARE_BITMAP(eligible_ptes, MAX_PTRS_PER_PTE);\n+\n+\t/*\n+\t * What a scan found and the collapse after it needs.  Live only between\n+\t * the two, and read by nobody else.\n+\t */\n+\n+\t/* Anonymous only: orders to try, referenced and swap PTE counts */\n+\tunsigned long scan_orders;\n+\tint scan_referenced;\n+\tint scan_unmapped;\n+\n+\t/*\n+\t * File only.  A file collapse works on the page cache and never sees a\n+\t * VMA, so the scan takes a reference to the file while it still has\n+\t * one, and the collapse gives it back.\n+\t */\n+\tstruct file *scan_file;\n+\tpgoff_t scan_pgoff;\n+};\n+\n+#endif\t/* __MM_COLLAPSE_H */\ndiff --git a/mm/khugepaged.c b/mm/khugepaged.c\nindex dbae78b68dd85..ef5cd6fda34f7 100644\n--- a/mm/khugepaged.c\n+++ b/mm/khugepaged.c\n@@ -26,44 +26,10 @@\n #include \u003clinux/cleanup.h\u003e\n \n #include \u003casm/tlb.h\u003e\n+#include \"collapse.h\"\n #include \"internal.h\"\n-#include \"page_alloc.h\"\n #include \"mm_slot.h\"\n-\n-enum scan_result {\n-\tSCAN_FAIL,\n-\tSCAN_SUCCEED,\n-\tSCAN_NO_PTE_TABLE,\n-\tSCAN_PMD_MAPPED,\n-\tSCAN_EXCEED_NONE_PTE,\n-\tSCAN_EXCEED_SWAP_PTE,\n-\tSCAN_EXCEED_SHARED_PTE,\n-\tSCAN_PTE_NON_PRESENT,\n-\tSCAN_PTE_UFFD,\n-\tSCAN_PTE_MAPPED_HUGEPAGE,\n-\tSCAN_LACK_REFERENCED_PAGE,\n-\tSCAN_PAGE_NULL,\n-\tSCAN_SCAN_ABORT,\n-\tSCAN_PAGE_COUNT,\n-\tSCAN_PAGE_LRU,\n-\tSCAN_PAGE_LOCK,\n-\tSCAN_PAGE_ANON,\n-\tSCAN_PAGE_LAZYFREE,\n-\tSCAN_PAGE_COMPOUND,\n-\tSCAN_ANY_PROCESS,\n-\tSCAN_VMA_NULL,\n-\tSCAN_VMA_CHECK,\n-\tSCAN_ADDRESS_RANGE,\n-\tSCAN_DEL_PAGE_LRU,\n-\tSCAN_ALLOC_HUGE_PAGE_FAIL,\n-\tSCAN_CGROUP_CHARGE_FAIL,\n-\tSCAN_TRUNCATED,\n-\tSCAN_PAGE_HAS_PRIVATE,\n-\tSCAN_STORE_FAILED,\n-\tSCAN_COPY_MC,\n-\tSCAN_PAGE_FILLED,\n-\tSCAN_PAGE_DIRTY_OR_WRITEBACK,\n-};\n+#include \"page_alloc.h\"\n \n #define CREATE_TRACE_POINTS\n #include \u003ctrace/events/huge_memory.h\u003e\n@@ -91,7 +57,6 @@ static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);\n  *\n  * Note that these are only respected if collapse was initiated by khugepaged.\n  */\n-#define KHUGEPAGED_MAX_PTES_LIMIT (HPAGE_PMD_NR - 1)\n unsigned int khugepaged_max_ptes_none __read_mostly;\n static unsigned int khugepaged_max_ptes_swap __read_mostly;\n static unsigned int khugepaged_max_ptes_shared __read_mostly;\n@@ -101,24 +66,6 @@ static DEFINE_READ_MOSTLY_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);\n \n static struct kmem_cache *mm_slot_cache __ro_after_init;\n \n-#define KHUGEPAGED_MIN_MTHP_ORDER\t2\n-\n-struct collapse_control {\n-\tbool is_khugepaged;\n-\n-\t/* Num pages scanned per node */\n-\tu32 node_load[MAX_NUMNODES];\n-\n-\t/* Num pages scanned (see khugepaged_pages_to_scan) */\n-\tunsigned int progress;\n-\n-\t/* nodemask for allocation fallback */\n-\tnodemask_t alloc_nmask;\n-\n-\t/* Each bit represents a single occupied (!none/zero) page. */\n-\tDECLARE_BITMAP(mthp_present_ptes, MAX_PTRS_PER_PTE);\n-};\n-\n /**\n  * struct khugepaged_scan - cursor for scanning\n  * @mm_head: the head of the mm list to scan\n@@ -267,7 +214,7 @@ static ssize_t max_ptes_none_store(struct kobject *kobj,\n \tunsigned long max_ptes_none;\n \n \terr = kstrtoul(buf, 10, \u0026max_ptes_none);\n-\tif (err || max_ptes_none \u003e KHUGEPAGED_MAX_PTES_LIMIT)\n+\tif (err || max_ptes_none \u003e COLLAPSE_MAX_PTES_LIMIT)\n \t\treturn -EINVAL;\n \n \tkhugepaged_max_ptes_none = max_ptes_none;\n@@ -292,7 +239,7 @@ static ssize_t max_ptes_swap_store(struct kobject *kobj,\n \tunsigned long max_ptes_swap;\n \n \terr  = kstrtoul(buf, 10, \u0026max_ptes_swap);\n-\tif (err || max_ptes_swap \u003e KHUGEPAGED_MAX_PTES_LIMIT)\n+\tif (err || max_ptes_swap \u003e COLLAPSE_MAX_PTES_LIMIT)\n \t\treturn -EINVAL;\n \n \tkhugepaged_max_ptes_swap = max_ptes_swap;\n@@ -318,7 +265,7 @@ static ssize_t max_ptes_shared_store(struct kobject *kobj,\n \tunsigned long max_ptes_shared;\n \n \terr  = kstrtoul(buf, 10, \u0026max_ptes_shared);\n-\tif (err || max_ptes_shared \u003e KHUGEPAGED_MAX_PTES_LIMIT)\n+\tif (err || max_ptes_shared \u003e COLLAPSE_MAX_PTES_LIMIT)\n \t\treturn -EINVAL;\n \n \tkhugepaged_max_ptes_shared = max_ptes_shared;\n@@ -367,30 +314,17 @@ static bool pte_none_or_zero(pte_t pte)\n static unsigned int collapse_max_ptes_none(struct collapse_control *cc,\n \t\tstruct vm_area_struct *vma, unsigned int order)\n {\n-\tconst unsigned int max_ptes_none = khugepaged_max_ptes_none;\n+\tunsigned int max_ptes_none;\n \n \tif (vma \u0026\u0026 userfaultfd_armed(vma))\n \t\treturn 0;\n-\t/* for MADV_COLLAPSE, allow any empty/shared zeropage PTEs */\n-\tif (!cc-\u003eis_khugepaged)\n-\t\treturn HPAGE_PMD_NR;\n-\t/* for PMD collapse, respect the user defined maximum */\n \tif (is_pmd_order(order))\n-\t\treturn max_ptes_none;\n-\t/*\n-\t * for mTHP collapse with the sysctl value set to KHUGEPAGED_MAX_PTES_LIMIT,\n-\t * scale the maximum number of PTEs to the order of the collapse.\n-\t */\n-\tif (max_ptes_none == KHUGEPAGED_MAX_PTES_LIMIT)\n+\t\treturn cc-\u003epolicy.pmd.max_ptes_none;\n+\n+\t/* Below PMD order: all but one PTE of the window, or none */\n+\tmax_ptes_none = cc-\u003epolicy.sub_pmd.max_ptes_none;\n+\tif (max_ptes_none == COLLAPSE_MAX_PTES_LIMIT)\n \t\treturn (1 \u003c\u003c order) - 1;\n-\t/*\n-\t * For mTHP collapse of values other than 0 or KHUGEPAGED_MAX_PTES_LIMIT,\n-\t * emit a warning and return 0.\n-\t */\n-\tif (max_ptes_none)\n-\t\tpr_warn_once(\"mTHP collapse does not support max_ptes_none\"\n-\t\t     \" values other than 0 or %u, defaulting to 0.\\n\",\n-\t\t     KHUGEPAGED_MAX_PTES_LIMIT);\n \treturn 0;\n }\n \n@@ -406,20 +340,9 @@ static unsigned int collapse_max_ptes_none(struct collapse_control *cc,\n static unsigned int collapse_max_ptes_shared(struct collapse_control *cc,\n \t\tunsigned int order)\n {\n-\t/*\n-\t * For MADV_COLLAPSE, do not restrict the number of PTEs that map shared\n-\t * anonymous pages.\n-\t */\n-\tif (!cc-\u003eis_khugepaged)\n-\t\treturn HPAGE_PMD_NR;\n-\t/*\n-\t * for mTHP collapse do not allow collapsing anonymous memory pages that\n-\t * are shared between processes.\n-\t */\n-\tif (!is_pmd_order(order))\n-\t\treturn 0;\n-\t/* for PMD collapse, respect the user defined maximum */\n-\treturn khugepaged_max_ptes_shared;\n+\tif (is_pmd_order(order))\n+\t\treturn cc-\u003epolicy.pmd.max_ptes_shared;\n+\treturn cc-\u003epolicy.sub_pmd.max_ptes_shared;\n }\n \n /**\n@@ -434,17 +357,9 @@ static unsigned int collapse_max_ptes_shared(struct collapse_control *cc,\n static unsigned int collapse_max_ptes_swap(struct collapse_control *cc,\n \t\tunsigned int order)\n {\n-\t/*\n-\t * For MADV_COLLAPSE, do not restrict the number PTEs entries or\n-\t * pagecache entries that are non-present.\n-\t */\n-\tif (!cc-\u003eis_khugepaged)\n-\t\treturn HPAGE_PMD_NR;\n-\t/* for mTHP collapse do not allow any non-present PTEs or pagecache entries */\n-\tif (!is_pmd_order(order))\n-\t\treturn 0;\n-\t/* for PMD collapse, respect the user defined maximum */\n-\treturn khugepaged_max_ptes_swap;\n+\tif (is_pmd_order(order))\n+\t\treturn cc-\u003epolicy.pmd.max_ptes_swap;\n+\treturn cc-\u003epolicy.sub_pmd.max_ptes_swap;\n }\n \n int hugepage_madvise(struct vm_area_struct *vma,\n@@ -476,7 +391,7 @@ int __init khugepaged_init(void)\n \t\treturn -ENOMEM;\n \n \tkhugepaged_pages_to_scan = HPAGE_PMD_NR * 8;\n-\tkhugepaged_max_ptes_none = KHUGEPAGED_MAX_PTES_LIMIT;\n+\tkhugepaged_max_ptes_none = COLLAPSE_MAX_PTES_LIMIT;\n \tkhugepaged_max_ptes_swap = HPAGE_PMD_NR / 8;\n \tkhugepaged_max_ptes_shared = HPAGE_PMD_NR / 2;\n \n@@ -579,17 +494,11 @@ static unsigned long collapse_possible_orders(struct vm_area_struct *vma,\n \treturn thp_vma_allowable_orders(vma, vm_flags, tva_flags, orders);\n }\n \n-static bool collapse_possible(struct vm_area_struct *vma,\n-\t\tvm_flags_t vm_flags, enum tva_type tva_flags)\n-{\n-\treturn collapse_possible_orders(vma, vm_flags, tva_flags);\n-}\n-\n void khugepaged_enter_vma(struct vm_area_struct *vma,\n \t\t\t  vm_flags_t vm_flags)\n {\n-\tif (!mm_flags_test(MMF_VM_HUGEPAGE, vma-\u003evm_mm) \u0026\u0026 hugepage_enabled()\n-\t    \u0026\u0026 collapse_possible(vma, vm_flags, TVA_KHUGEPAGED))\n+\tif (!mm_flags_test(MMF_VM_HUGEPAGE, vma-\u003evm_mm) \u0026\u0026 hugepage_enabled() \u0026\u0026\n+\t    collapse_possible_orders(vma, vm_flags, TVA_KHUGEPAGED))\n \t\t__khugepaged_enter(vma-\u003evm_mm);\n }\n \n@@ -623,11 +532,11 @@ void __khugepaged_exit(struct mm_struct *mm)\n \t}\n }\n \n-static void collapse_control_init_scan(struct collapse_control *cc)\n+static void collapse_scan_reset(struct collapse_control *cc)\n {\n \tmemset(cc-\u003enode_load, 0, sizeof(cc-\u003enode_load));\n \tnodes_clear(cc-\u003ealloc_nmask);\n-\tbitmap_zero(cc-\u003emthp_present_ptes, MAX_PTRS_PER_PTE);\n+\tbitmap_zero(cc-\u003eeligible_ptes, MAX_PTRS_PER_PTE);\n }\n \n static void release_pte_folio(struct folio *folio)\n@@ -731,13 +640,13 @@ static enum scan_result __collapse_huge_page_isolate(struct vm_area_struct *vma,\n \t\t * If the vma has the VM_DROPPABLE flag, the collapse will\n \t\t * preserve the lazyfree property without needing to skip.\n \t\t */\n-\t\tif (cc-\u003eis_khugepaged \u0026\u0026 !(vma-\u003evm_flags \u0026 VM_DROPPABLE) \u0026\u0026\n+\t\tif (cc-\u003epolicy.anon_skip_lazyfree \u0026\u0026 !(vma-\u003evm_flags \u0026 VM_DROPPABLE) \u0026\u0026\n \t\t    folio_test_lazyfree(folio) \u0026\u0026 !pte_dirty(pteval)) {\n \t\t\tresult = SCAN_PAGE_LAZYFREE;\n \t\t\tgoto out;\n \t\t}\n \n-\t\t/* See collapse_scan_pmd(). */\n+\t\t/* See collapse_scan_anon(). */\n \t\tif (folio_maybe_mapped_shared(folio)) {\n \t\t\t/*\n \t\t\t * TODO: Support shared pages without leading to further\n@@ -820,12 +729,12 @@ static enum scan_result __collapse_huge_page_isolate(struct vm_area_struct *vma,\n \t\tif (folio_test_large(folio))\n \t\t\tlist_add_tail(\u0026folio-\u003elru, compound_pagelist);\n next:\n-\t\tif (cc-\u003eis_khugepaged \u0026\u0026\n+\t\tif (cc-\u003epolicy.anon_require_referenced \u0026\u0026\n \t\t    folio_pte_referenced(folio, vma, addr, pteval))\n \t\t\treferenced++;\n \t}\n \n-\tif (unlikely(cc-\u003eis_khugepaged \u0026\u0026 !referenced)) {\n+\tif (unlikely(cc-\u003epolicy.anon_require_referenced \u0026\u0026 !referenced)) {\n \t\tresult = SCAN_LACK_REFERENCED_PAGE;\n \t} else {\n \t\tresult = SCAN_SUCCEED;\n@@ -991,9 +900,7 @@ static void khugepaged_alloc_sleep(void)\n \tremove_wait_queue(\u0026khugepaged_wait, \u0026wait);\n }\n \n-static struct collapse_control khugepaged_collapse_control = {\n-\t.is_khugepaged = true,\n-};\n+static struct collapse_control khugepaged_collapse_control;\n \n static bool collapse_scan_abort(int nid, struct collapse_control *cc)\n {\n@@ -1029,6 +936,52 @@ static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)\n \treturn khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT;\n }\n \n+/* khugepaged collapses on its own initiative, so it obeys its own settings */\n+static void collapse_policy_khugepaged(struct collapse_policy *p)\n+{\n+\tp-\u003epmd.max_ptes_none = READ_ONCE(khugepaged_max_ptes_none);\n+\tp-\u003epmd.max_ptes_swap = READ_ONCE(khugepaged_max_ptes_swap);\n+\tp-\u003epmd.max_ptes_shared = READ_ONCE(khugepaged_max_ptes_shared);\n+\n+\t/*\n+\t * A sub-PMD window takes no swapped-out and no shared PTE: reading\n+\t * pages back or breaking CoW is not worth it for an mTHP.  Empty PTEs\n+\t * it takes all or nothing, since anything in between would let one\n+\t * collapse feed the next.\n+\t */\n+\tp-\u003esub_pmd.max_ptes_none = p-\u003epmd.max_ptes_none;\n+\tif (p-\u003esub_pmd.max_ptes_none \u0026\u0026\n+\t    p-\u003esub_pmd.max_ptes_none != COLLAPSE_MAX_PTES_LIMIT)\n+\t\tpr_warn_once(\"mTHP collapse does not support max_ptes_none values other than 0 or %u, defaulting to 0.\\n\",\n+\t\t\t     COLLAPSE_MAX_PTES_LIMIT);\n+\tp-\u003esub_pmd.max_ptes_swap = 0;\n+\tp-\u003esub_pmd.max_ptes_shared = 0;\n+\n+\tp-\u003eanon_skip_lazyfree = true;\n+\tp-\u003eanon_require_referenced = true;\n+\tp-\u003efile_install_pmd = false;\n+\tp-\u003efile_writeback_dirty = false;\n+\tp-\u003egfp = alloc_hugepage_khugepaged_gfpmask();\n+\tp-\u003etva_type = TVA_KHUGEPAGED;\n+}\n+\n+/* MADV_COLLAPSE was asked for explicitly, so it is not held to those */\n+static void collapse_policy_madvise(struct collapse_policy *p)\n+{\n+\tp-\u003epmd.max_ptes_none = HPAGE_PMD_NR;\n+\tp-\u003epmd.max_ptes_swap = HPAGE_PMD_NR;\n+\tp-\u003epmd.max_ptes_shared = HPAGE_PMD_NR;\n+\t/* Never read: MADV_COLLAPSE collapses to PMD order only */\n+\tp-\u003esub_pmd = p-\u003epmd;\n+\n+\tp-\u003eanon_skip_lazyfree = false;\n+\tp-\u003eanon_require_referenced = false;\n+\tp-\u003efile_install_pmd = true;\n+\tp-\u003efile_writeback_dirty = true;\n+\tp-\u003egfp = GFP_TRANSHUGE;\n+\tp-\u003etva_type = TVA_FORCED_COLLAPSE;\n+}\n+\n #ifdef CONFIG_NUMA\n static int collapse_find_target_node(struct collapse_control *cc)\n {\n@@ -1066,8 +1019,7 @@ static enum scan_result hugepage_vma_revalidate(struct mm_struct *mm, unsigned l\n \t\tstruct collapse_control *cc, unsigned int order)\n {\n \tstruct vm_area_struct *vma;\n-\tenum tva_type type = cc-\u003eis_khugepaged ? TVA_KHUGEPAGED :\n-\t\t\t\t TVA_FORCED_COLLAPSE;\n+\tenum tva_type type = cc-\u003epolicy.tva_type;\n \n \tif (unlikely(collapse_test_exit_or_disable(mm)))\n \t\treturn SCAN_ANY_PROCESS;\n@@ -1147,7 +1099,7 @@ static enum scan_result check_pmd_still_valid(struct mm_struct *mm,\n \n /*\n  * Bring missing pages in from swap, to complete THP collapse.\n- * Only done if collapse_scan_pmd() believes it is worthwhile.\n+ * Only done if collapse_scan_anon() believes it is worthwhile.\n  *\n  * For mTHP orders the function bails on the first swap entry, because\n  * faulting pages back in during collapse could re-populate PTEs that\n@@ -1250,8 +1202,7 @@ static enum scan_result __collapse_huge_page_swapin(struct mm_struct *mm,\n static enum scan_result alloc_charge_folio(struct folio **foliop, struct mm_struct *mm,\n \t\tstruct collapse_control *cc, unsigned int order)\n {\n-\tgfp_t gfp = (cc-\u003eis_khugepaged ? alloc_hugepage_khugepaged_gfpmask() :\n-\t\t     GFP_TRANSHUGE);\n+\tgfp_t gfp = cc-\u003epolicy.gfp;\n \tint node = collapse_find_target_node(cc);\n \tstruct folio *folio;\n \n@@ -1301,8 +1252,8 @@ static pgtable_t alloc_deposit_pte_table(struct mm_struct *mm)\n  * while allocating a THP, as that could trigger direct reclaim/compaction.\n  * Note that the VMA must be rechecked after grabbing the mmap_lock again.\n  */\n-static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long start_addr,\n-\t\tint referenced, int unmapped, struct collapse_control *cc,\n+static enum scan_result collapse_huge_page(struct mm_struct *mm,\n+\t\tunsigned long start_addr, struct collapse_control *cc,\n \t\tunsigned int order)\n {\n \tconst unsigned long pmd_addr = start_addr \u0026 HPAGE_PMD_MASK;\n@@ -1349,14 +1300,14 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long s\n \t\tgoto out_nolock;\n \t}\n \n-\tif (unmapped) {\n+\tif (cc-\u003escan_unmapped) {\n \t\t/*\n \t\t * __collapse_huge_page_swapin() will return with mmap_lock\n \t\t * released when it fails. So we jump out_nolock directly in\n \t\t * that case.  Continuing to collapse causes inconsistency.\n \t\t */\n \t\tresult = __collapse_huge_page_swapin(mm, vma, start_addr, pmd,\n-\t\t\t\t\t\t     referenced, order);\n+\t\t\t\t\t\t     cc-\u003escan_referenced, order);\n \t\tif (result != SCAN_SUCCEED)\n \t\t\tgoto out_nolock;\n \t}\n@@ -1509,27 +1460,26 @@ static unsigned int max_order_from_offset(unsigned int offset)\n }\n \n /*\n- * mthp_collapse() consumes the bitmap that is generated during\n- * collapse_scan_pmd() to determine what regions and mTHP orders fit best.\n+ * collapse_anon() consumes the bitmap that is generated during\n+ * collapse_scan_anon() to determine what regions and mTHP orders fit best.\n  *\n- * Each bit in cc-\u003emthp_present_ptes represents a single occupied (!none/zero)\n- * page. We start at the PMD order and check if it is eligible for collapse;\n+ * Each bit in cc-\u003eeligible_ptes marks a PTE the scan accepted as a collapse\n+ * source. We start at the PMD order and check if it is eligible for collapse;\n  * if not, we check the left and right halves of the PTE page table we are\n  * examining at a lower order.\n  *\n- * For each of these, we determine how many PTE entries are occupied in the\n- * range of PTE entries we propose to collapse, then we compare this to a\n- * threshold number of PTE entries which would need to be occupied for a\n- * collapse to be permitted at that order (accounting for max_ptes_none).\n+ * For each of these, we count the eligible PTEs in the range we propose to\n+ * collapse, then we compare this to the number of eligible PTEs the range\n+ * would need for a collapse to be permitted at that order (accounting for\n+ * max_ptes_none).\n  *\n  * If a collapse is permitted, we attempt to collapse the PTE range into a\n  * mTHP.\n  */\n-static enum scan_result mthp_collapse(struct mm_struct *mm,\n-\t\tunsigned long address, int referenced, int unmapped,\n-\t\tstruct collapse_control *cc, unsigned long enabled_orders)\n+static enum scan_result collapse_anon(struct mm_struct *mm,\n+\t\tunsigned long address, struct collapse_control *cc)\n {\n-\tunsigned int nr_occupied_ptes, nr_ptes, max_ptes_none;\n+\tunsigned int nr_eligible_ptes, nr_ptes, max_ptes_none;\n \tenum scan_result last_result = SCAN_FAIL;\n \tint collapsed = 0;\n \tbool alloc_failed = false;\n@@ -1540,27 +1490,26 @@ static enum scan_result mthp_collapse(struct mm_struct *mm,\n \twhile (offset \u003c HPAGE_PMD_NR) {\n \t\tnr_ptes = 1UL \u003c\u003c order;\n \n-\t\tif (!test_bit(order, \u0026enabled_orders))\n+\t\tif (!test_bit(order, \u0026cc-\u003escan_orders))\n \t\t\tgoto next_order;\n \n \t\tmax_ptes_none = collapse_max_ptes_none(cc, NULL, order);\n-\t\tnr_occupied_ptes = bitmap_weight_from(cc-\u003emthp_present_ptes, offset,\n+\t\tnr_eligible_ptes = bitmap_weight_from(cc-\u003eeligible_ptes, offset,\n \t\t\t\t\t\t      offset + nr_ptes);\n \n \t\t/*\n-\t\t * Swap PTEs accepted during the scan are counted in @unmapped,\n-\t\t * not in the present-PTE bitmap. Account them for the PMD-order\n-\t\t * candidate.\n+\t\t * Swap PTEs accepted during the scan are counted in\n+\t\t * cc-\u003escan_unmapped, not in cc-\u003eeligible_ptes. Account them for\n+\t\t * the PMD-order candidate.\n \t\t */\n \t\tif (is_pmd_order(order))\n-\t\t\tnr_occupied_ptes += unmapped;\n+\t\t\tnr_eligible_ptes += cc-\u003escan_unmapped;\n \n-\t\tif (nr_occupied_ptes \u003e= nr_ptes - max_ptes_none) {\n+\t\tif (nr_eligible_ptes \u003e= nr_ptes - max_ptes_none) {\n \t\t\tenum scan_result ret;\n \n \t\t\tcollapse_address = address + offset * PAGE_SIZE;\n-\t\t\tret = collapse_huge_page(mm, collapse_address, referenced,\n-\t\t\t\t\t\t unmapped, cc, order);\n+\t\t\tret = collapse_huge_page(mm, collapse_address, cc, order);\n \n \t\t\tswitch (ret) {\n \t\t\t/* Cases where we continue to next collapse candidate */\n@@ -1601,8 +1550,8 @@ static enum scan_result mthp_collapse(struct mm_struct *mm,\n \t\t * any smaller order enabled. When at the smallest order\n \t\t * we must always move to the next offset.\n \t\t */\n-\t\tif (order \u003e KHUGEPAGED_MIN_MTHP_ORDER \u0026\u0026\n-\t\t\t(enabled_orders \u0026 GENMASK(order - 1, 0))) {\n+\t\tif (order \u003e COLLAPSE_MIN_MTHP_ORDER \u0026\u0026\n+\t\t    (cc-\u003escan_orders \u0026 GENMASK(order - 1, 0))) {\n \t\t\torder--;\n \t\t\tcontinue;\n \t\t}\n@@ -1627,14 +1576,14 @@ static enum scan_result mthp_collapse(struct mm_struct *mm,\n \treturn last_result;\n }\n \n-static enum scan_result collapse_scan_pmd(struct mm_struct *mm,\n-\t\tstruct vm_area_struct *vma, unsigned long start_addr,\n-\t\tbool *lock_dropped, struct collapse_control *cc)\n+static enum scan_result collapse_scan_anon(struct vm_area_struct *vma,\n+\t\tunsigned long start_addr, struct collapse_control *cc)\n {\n \tconst unsigned int max_ptes_shared = collapse_max_ptes_shared(cc, HPAGE_PMD_ORDER);\n \tconst unsigned int max_ptes_swap = collapse_max_ptes_swap(cc, HPAGE_PMD_ORDER);\n \tunsigned int max_ptes_none = collapse_max_ptes_none(cc, vma, HPAGE_PMD_ORDER);\n-\tenum tva_type tva_flags = cc-\u003eis_khugepaged ? TVA_KHUGEPAGED : TVA_FORCED_COLLAPSE;\n+\tenum tva_type tva_flags = cc-\u003epolicy.tva_type;\n+\tstruct mm_struct *mm = vma-\u003evm_mm;\n \tpmd_t *pmd;\n \tpte_t *pte, *_pte, pteval;\n \tint i;\n@@ -1656,17 +1605,17 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,\n \t\tgoto out;\n \t}\n \n-\tcollapse_control_init_scan(cc);\n+\tcollapse_scan_reset(cc);\n \n \tenabled_orders = collapse_possible_orders(vma, vma-\u003evm_flags, tva_flags);\n \n \t/*\n \t * If PMD is the only enabled order, enforce max_ptes_none, otherwise\n \t * scan all pages to populate the bitmap for mTHP collapse. The bitmap\n-\t * is then checked again in mthp_collapse() for each attempted order.\n+\t * is then checked again in collapse_anon() for each attempted order.\n \t */\n \tif (enabled_orders != BIT(HPAGE_PMD_ORDER))\n-\t\tmax_ptes_none = KHUGEPAGED_MAX_PTES_LIMIT;\n+\t\tmax_ptes_none = COLLAPSE_MAX_PTES_LIMIT;\n \n \tpte = pte_offset_map_lock(mm, pmd, start_addr, \u0026ptl);\n \tif (!pte) {\n@@ -1734,7 +1683,7 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,\n \t\t * If the vma has the VM_DROPPABLE flag, the collapse will\n \t\t * preserve the lazyfree property without needing to skip.\n \t\t */\n-\t\tif (cc-\u003eis_khugepaged \u0026\u0026 !(vma-\u003evm_flags \u0026 VM_DROPPABLE) \u0026\u0026\n+\t\tif (cc-\u003epolicy.anon_skip_lazyfree \u0026\u0026 !(vma-\u003evm_flags \u0026 VM_DROPPABLE) \u0026\u0026\n \t\t    folio_test_lazyfree(folio) \u0026\u0026 !pte_dirty(pteval)) {\n \t\t\tresult = SCAN_PAGE_LAZYFREE;\n \t\t\tfailed_pfn = folio_pfn(folio);\n@@ -1761,8 +1710,8 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,\n \t\t\t}\n \t\t}\n \n-\t\t/* Set bit for occupied pages */\n-\t\t__set_bit(i, cc-\u003emthp_present_ptes);\n+\t\t/* The scan accepted this PTE as a collapse source */\n+\t\t__set_bit(i, cc-\u003eeligible_ptes);\n \t\t/*\n \t\t * Record which node the original page is from and save this\n \t\t * information to cc-\u003enode_load[].\n@@ -1800,13 +1749,13 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,\n \t\t\tgoto out_unmap;\n \t\t}\n \n-\t\tif (cc-\u003eis_khugepaged \u0026\u0026\n+\t\tif (cc-\u003epolicy.anon_require_referenced \u0026\u0026\n \t\t    folio_pte_referenced(folio, vma, addr, pteval))\n \t\t\treferenced++;\n \t}\n-\tif (cc-\u003eis_khugepaged \u0026\u0026\n-\t\t   (!referenced ||\n-\t\t    (unmapped \u0026\u0026 referenced \u003c HPAGE_PMD_NR / 2))) {\n+\tif (cc-\u003epolicy.anon_require_referenced \u0026\u0026\n+\t    (!referenced ||\n+\t     (unmapped \u0026\u0026 referenced \u003c HPAGE_PMD_NR / 2))) {\n \t\tresult = SCAN_LACK_REFERENCED_PAGE;\n \t} else {\n \t\tresult = SCAN_SUCCEED;\n@@ -1814,12 +1763,9 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,\n out_unmap:\n \tpte_unmap_unlock(pte, ptl);\n \tif (result == SCAN_SUCCEED) {\n-\t\t/* collapse_huge_page() expects the lock to be dropped before calling */\n-\t\tmmap_read_unlock(mm);\n-\t\tresult = mthp_collapse(mm, start_addr, referenced,\n-\t\t\t\t       unmapped, cc, enabled_orders);\n-\t\t/* mmap_lock was released above, set lock_dropped */\n-\t\t*lock_dropped = true;\n+\t\tcc-\u003escan_orders = enabled_orders;\n+\t\tcc-\u003escan_referenced = referenced;\n+\t\tcc-\u003escan_unmapped = unmapped;\n \t}\n out:\n \ttrace_mm_khugepaged_scan_pmd(mm, failed_pfn, referenced,\n@@ -2665,11 +2611,11 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,\n \txas_unlock_irq(\u0026xas);\n \n \t/*\n-\t * Remove pte page tables, so we can re-fault the page as huge.\n-\t * If MADV_COLLAPSE, adjust result to call try_collapse_pte_mapped_thp().\n+\t * Remove pte page tables, so we can re-fault the page as huge.  A\n+\t * caller that wants the PMD mapped now is told to go and do that.\n \t */\n \tretract_page_tables(mapping, start);\n-\tif (cc \u0026\u0026 !cc-\u003eis_khugepaged)\n+\tif (cc-\u003epolicy.file_install_pmd)\n \t\tresult = SCAN_PTE_MAPPED_HUGEPAGE;\n \tfolio_unlock(new_folio);\n \n@@ -2734,7 +2680,7 @@ static enum scan_result collapse_scan_file(struct mm_struct *mm,\n \n \tpresent = 0;\n \tswap = 0;\n-\tcollapse_control_init_scan(cc);\n+\tcollapse_scan_reset(cc);\n \trcu_read_lock();\n \txas_for_each(\u0026xas, folio, start + HPAGE_PMD_NR - 1) {\n \t\tif (xas_retry(\u0026xas, folio))\n@@ -2816,53 +2762,78 @@ static enum scan_result collapse_scan_file(struct mm_struct *mm,\n \telse\n \t\tcc-\u003eprogress += HPAGE_PMD_NR;\n \n-\tif (result == SCAN_SUCCEED) {\n-\t\tif (present \u003c HPAGE_PMD_NR - max_ptes_none) {\n-\t\t\tresult = SCAN_EXCEED_NONE_PTE;\n-\t\t\tcount_vm_event(THP_SCAN_EXCEED_NONE_PTE);\n-\t\t} else {\n-\t\t\tresult = collapse_file(mm, addr, file, start, cc);\n-\t\t}\n+\tif (result == SCAN_SUCCEED \u0026\u0026 present \u003c HPAGE_PMD_NR - max_ptes_none) {\n+\t\tresult = SCAN_EXCEED_NONE_PTE;\n+\t\tcount_vm_event(THP_SCAN_EXCEED_NONE_PTE);\n \t}\n \n-\ttrace_mm_khugepaged_scan_file(mm, failed_pfn, file, present, swap, result);\n+\ttrace_mm_khugepaged_scan_file(mm, failed_pfn, file, present, swap,\n+\t\t\t\t      result);\n \treturn result;\n }\n \n-/*\n- * Try to collapse a single PMD starting at a PMD aligned addr, and return\n- * the results.\n- */\n-static enum scan_result collapse_single_pmd(unsigned long addr,\n-\t\tstruct vm_area_struct *vma, bool *lock_dropped,\n-\t\tstruct collapse_control *cc)\n+static void collapse_control_init(struct collapse_control *cc)\n+{\n+\tcc-\u003eprogress = 0;\n+\tcc-\u003escan_file = NULL;\n+}\n+\n+static enum scan_result collapse_scan_pmd(struct vm_area_struct *vma,\n+\t\tunsigned long addr, struct collapse_control *cc)\n {\n-\tstruct mm_struct *mm = vma-\u003evm_mm;\n-\tbool triggered_wb = false;\n \tenum scan_result result;\n-\tstruct file *file;\n \tpgoff_t pgoff;\n \n-\tmmap_assert_locked(mm);\n-\n-\tif (vma_is_anonymous(vma)) {\n-\t\tresult = collapse_scan_pmd(mm, vma, addr, lock_dropped, cc);\n-\t\tgoto end;\n+\tmmap_assert_locked(vma-\u003evm_mm);\n+\t/* A scan that found work has to have been followed by collapse_pmd() */\n+\tif (WARN_ON_ONCE(cc-\u003escan_file)) {\n+\t\tfput(cc-\u003escan_file);\n+\t\tcc-\u003escan_file = NULL;\n \t}\n \n-\tfile = get_file(vma-\u003evm_file);\n-\tpgoff = linear_page_index(vma, addr);\n+\tif (vma_is_anonymous(vma))\n+\t\treturn collapse_scan_anon(vma, addr, cc);\n \n-\tmmap_read_unlock(mm);\n-\t*lock_dropped = true;\n-retry:\n-\tresult = collapse_scan_file(mm, addr, file, pgoff, cc);\n+\tpgoff = linear_page_index(vma, addr);\n+\tresult = collapse_scan_file(vma-\u003evm_mm, addr, vma-\u003evm_file, pgoff, cc);\n+\t/*\n+\t * SCAN_PTE_MAPPED_HUGEPAGE is work too: the page cache already holds\n+\t * the PMD folio, and collapse_pmd() still has to retract the PTE table.\n+\t */\n+\tif (result != SCAN_SUCCEED \u0026\u0026 result != SCAN_PTE_MAPPED_HUGEPAGE)\n+\t\treturn result;\n \n \t/*\n-\t * For MADV_COLLAPSE, when encountering dirty pages, try to writeback,\n-\t * then retry the collapse one time.\n+\t * A file collapse works on the page cache and never sees a VMA, so take\n+\t * what it needs from this one while it is still here.\n \t */\n-\tif (!cc-\u003eis_khugepaged \u0026\u0026 result == SCAN_PAGE_DIRTY_OR_WRITEBACK \u0026\u0026\n+\tcc-\u003escan_file = get_file(vma-\u003evm_file);\n+\tcc-\u003escan_pgoff = pgoff;\n+\treturn result;\n+}\n+\n+static enum scan_result collapse_pmd(struct mm_struct *mm,\n+\t\tunsigned long addr, enum scan_result result,\n+\t\tstruct collapse_control *cc)\n+{\n+\tstruct file *file = cc-\u003escan_file;\n+\tbool triggered_wb = false;\n+\tpgoff_t pgoff;\n+\n+\tif (!file)\n+\t\treturn collapse_anon(mm, addr, cc);\n+\n+\tcc-\u003escan_file = NULL;\n+\tpgoff = cc-\u003escan_pgoff;\n+\n+\t/* The scan found the PMD folio in place: nothing to collapse */\n+\tif (result == SCAN_PTE_MAPPED_HUGEPAGE)\n+\t\tgoto put;\n+retry:\n+\tresult = collapse_file(mm, addr, file, pgoff, cc);\n+\n+\t/* Dirty pages are worth a writeback and one more try, if asked for */\n+\tif (cc-\u003epolicy.file_writeback_dirty \u0026\u0026 result == SCAN_PAGE_DIRTY_OR_WRITEBACK \u0026\u0026\n \t    !triggered_wb \u0026\u0026 mapping_can_writeback(file-\u003ef_mapping)) {\n \t\tconst loff_t lstart = (loff_t)pgoff \u003c\u003c PAGE_SHIFT;\n \t\tconst loff_t lend = lstart + HPAGE_PMD_SIZE - 1;\n@@ -2871,25 +2842,49 @@ static enum scan_result collapse_single_pmd(unsigned long addr,\n \t\ttriggered_wb = true;\n \t\tgoto retry;\n \t}\n+put:\n \tfput(file);\n \n+\t/*\n+\t * A PMD folio is in the page cache, whether the collapse just put it\n+\t * there or found it: retract the PTE table, and map the PMD if asked.\n+\t */\n \tif (result == SCAN_PTE_MAPPED_HUGEPAGE) {\n \t\tmmap_read_lock(mm);\n \t\tif (collapse_test_exit_or_disable(mm))\n \t\t\tresult = SCAN_ANY_PROCESS;\n \t\telse\n \t\t\tresult = try_collapse_pte_mapped_thp(mm, addr,\n-\t\t\t\t\t\t\t     !cc-\u003eis_khugepaged);\n+\t\t\t\t\t\t\tcc-\u003epolicy.file_install_pmd);\n \t\tif (result == SCAN_PMD_MAPPED)\n \t\t\tresult = SCAN_SUCCEED;\n \t\tmmap_read_unlock(mm);\n \t}\n-end:\n-\tif (cc-\u003eis_khugepaged \u0026\u0026 result == SCAN_SUCCEED)\n-\t\t++khugepaged_pages_collapsed;\n \treturn result;\n }\n \n+/*\n+ * Try to collapse a single PMD starting at a PMD aligned addr, and return\n+ * the results.\n+ */\n+static enum scan_result collapse_single_pmd(unsigned long addr,\n+\t\tstruct vm_area_struct *vma, bool *lock_dropped,\n+\t\tstruct collapse_control *cc)\n+{\n+\tstruct mm_struct *mm = vma-\u003evm_mm;\n+\tenum scan_result result;\n+\n+\tresult = collapse_scan_pmd(vma, addr, cc);\n+\tif (result != SCAN_SUCCEED \u0026\u0026 result != SCAN_PTE_MAPPED_HUGEPAGE)\n+\t\treturn result;\n+\n+\t/* The collapse takes its own locks, so give this up */\n+\tmmap_read_unlock(mm);\n+\t*lock_dropped = true;\n+\n+\treturn collapse_pmd(mm, addr, result, cc);\n+}\n+\n static void collapse_scan_mm_slot(unsigned int progress_max,\n \t\tenum scan_result *result, struct collapse_control *cc)\n \t__releases(\u0026khugepaged_mm_lock)\n@@ -2936,7 +2931,8 @@ static void collapse_scan_mm_slot(unsigned int progress_max,\n \t\t\tcc-\u003eprogress++;\n \t\t\tbreak;\n \t\t}\n-\t\tif (!collapse_possible(vma, vma-\u003evm_flags, TVA_KHUGEPAGED)) {\n+\t\tif (!collapse_possible_orders(vma, vma-\u003evm_flags,\n+\t\t\t\t\t      TVA_KHUGEPAGED)) {\n \t\t\tcc-\u003eprogress++;\n \t\t\tcontinue;\n \t\t}\n@@ -2963,6 +2959,8 @@ static void collapse_scan_mm_slot(unsigned int progress_max,\n \n \t\t\t*result = collapse_single_pmd(khugepaged_scan.address,\n \t\t\t\t\t\t      vma, \u0026lock_dropped, cc);\n+\t\t\tif (*result == SCAN_SUCCEED)\n+\t\t\t\tkhugepaged_pages_collapsed++;\n \t\t\t/* move to next address */\n \t\t\tkhugepaged_scan.address += HPAGE_PMD_SIZE;\n \t\t\tif (lock_dropped)\n@@ -3029,7 +3027,9 @@ static void khugepaged_do_scan(struct collapse_control *cc)\n \n \tlru_add_drain_all();\n \n-\tcc-\u003eprogress = 0;\n+\tcollapse_control_init(cc);\n+\tcollapse_policy_khugepaged(\u0026cc-\u003epolicy);\n+\n \twhile (true) {\n \t\tcond_resched();\n \n@@ -3244,7 +3244,7 @@ int madvise_collapse(struct vm_area_struct *vma, unsigned long start,\n \tBUG_ON(vma-\u003evm_start \u003e start);\n \tBUG_ON(vma-\u003evm_end \u003c end);\n \n-\tif (!collapse_possible(vma, vma-\u003evm_flags, TVA_FORCED_COLLAPSE))\n+\tif (!collapse_possible_orders(vma, vma-\u003evm_flags, TVA_FORCED_COLLAPSE))\n \t\treturn -EINVAL;\n \n \thstart = ALIGN(start, HPAGE_PMD_SIZE);\n@@ -3256,10 +3256,9 @@ int madvise_collapse(struct vm_area_struct *vma, unsigned long start,\n \tcc = kmalloc_obj(*cc);\n \tif (!cc)\n \t\treturn -ENOMEM;\n-\tcc-\u003eis_khugepaged = false;\n-\tcc-\u003eprogress = 0;\n+\tcollapse_control_init(cc);\n+\tcollapse_policy_madvise(\u0026cc-\u003epolicy);\n \n-\tmmgrab(mm);\n \tlru_add_drain_all();\n \n \tfor (addr = hstart; addr \u003c hend; addr += HPAGE_PMD_SIZE) {\n@@ -3315,7 +3314,6 @@ int madvise_collapse(struct vm_area_struct *vma, unsigned long start,\n \t}\n out_nolock:\n \tmmap_assert_locked(mm);\n-\tmmdrop(mm);\n \tkfree(cc);\n \n \treturn thps == ((hend - hstart) \u003e\u003e HPAGE_PMD_SHIFT) ? 0\n"
}

2/1 2026/10/14 23:14 agent patch-evaluator
1m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "TRANSPARENT_HUGEPAGE"
  ],
  "FocusSymbols": [
    "madvise_collapse",
    "collapse_single_pmd",
    "collapse_scan_pmd",
    "collapse_pmd",
    "collapse_anon",
    "collapse_scan_anon",
    "collapse_file",
    "collapse_scan_file",
    "khugepaged_do_scan"
  ],
  "Reasoning": "The patch refactors transparent huge page (THP) collapse logic in mm/khugepaged.c and introduces mm/collapse.h. It decouples scan and collapse phases into separate functions (collapse_scan_pmd, collapse_scan_anon, collapse_pmd, collapse_anon), formalizes collapse policies/limits between background khugepaged and MADV_COLLAPSE, alters file reference handling (with a new WARN_ON_ONCE assertion checking cc-\u003escan_file), and modifies reference management in madvise_collapse. This reachable core memory management code is actively exercised via madvise(MADV_COLLAPSE) and the khugepaged kthread.",
  "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 ff94c96f8aca60d916dea20b7f431378dd8e74b0
Author: syz-cluster <triage@syzkaller.com>
Date:   Wed Oct 14 23:14:02 2026 +0000

    syz-cluster: applied patch under review

diff --git a/MAINTAINERS b/MAINTAINERS
index 39abe7378b6fc..5c38da7090db8 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -17452,6 +17452,7 @@ F:	Documentation/admin-guide/mm/transhuge.rst
 F:	include/linux/huge_mm.h
 F:	include/linux/khugepaged.h
 F:	include/trace/events/huge_memory.h
+F:	mm/collapse.h
 F:	mm/huge_memory.c
 F:	mm/khugepaged.c
 F:	mm/mm_slot.h
diff --git a/mm/collapse.h b/mm/collapse.h
new file mode 100644
index 0000000000000..759ec9cd45414
--- /dev/null
+++ b/mm/collapse.h
@@ -0,0 +1,121 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __MM_COLLAPSE_H
+#define __MM_COLLAPSE_H
+
+#include <linux/mm.h>
+#include <linux/nodemask.h>
+#include <linux/pgtable.h>
+#include <linux/types.h>
+
+#define COLLAPSE_MAX_PTES_LIMIT		(HPAGE_PMD_NR - 1)
+#define COLLAPSE_MIN_MTHP_ORDER		2
+
+enum scan_result {
+	SCAN_FAIL,
+	SCAN_SUCCEED,
+	SCAN_NO_PTE_TABLE,
+	SCAN_PMD_MAPPED,
+	SCAN_EXCEED_NONE_PTE,
+	SCAN_EXCEED_SWAP_PTE,
+	SCAN_EXCEED_SHARED_PTE,
+	SCAN_PTE_NON_PRESENT,
+	SCAN_PTE_UFFD,
+	SCAN_PTE_MAPPED_HUGEPAGE,
+	SCAN_LACK_REFERENCED_PAGE,
+	SCAN_PAGE_NULL,
+	SCAN_SCAN_ABORT,
+	SCAN_PAGE_COUNT,
+	SCAN_PAGE_LRU,
+	SCAN_PAGE_LOCK,
+	SCAN_PAGE_ANON,
+	SCAN_PAGE_LAZYFREE,
+	SCAN_PAGE_COMPOUND,
+	SCAN_ANY_PROCESS,
+	SCAN_VMA_NULL,
+	SCAN_VMA_CHECK,
+	SCAN_ADDRESS_RANGE,
+	SCAN_DEL_PAGE_LRU,
+	SCAN_ALLOC_HUGE_PAGE_FAIL,
+	SCAN_CGROUP_CHARGE_FAIL,
+	SCAN_TRUNCATED,
+	SCAN_PAGE_HAS_PRIVATE,
+	SCAN_STORE_FAILED,
+	SCAN_COPY_MC,
+	SCAN_PAGE_FILLED,
+	SCAN_PAGE_DIRTY_OR_WRITEBACK,
+};
+
+/* How many PTEs of a window may be missing, swapped out or shared */
+struct collapse_limits {
+	/* Counted over a PMD-sized window; HPAGE_PMD_NR means "no limit" */
+	unsigned int max_ptes_none;
+	unsigned int max_ptes_swap;
+	unsigned int max_ptes_shared;
+};
+
+/* What a collapse is allowed to do, decided by the caller that asks for it */
+struct collapse_policy {
+	/* Limits for a PMD-sized window */
+	struct collapse_limits pmd;
+
+	/*
+	 * Limits for a smaller window.  Its max_ptes_none is either 0 or
+	 * COLLAPSE_MAX_PTES_LIMIT, the latter meaning all but one PTE of the
+	 * window whatever its order; any other value counts as 0.
+	 */
+	struct collapse_limits sub_pmd;
+
+	/* Leave clean lazyfree folios to reclaim rather than collapse them */
+	bool anon_skip_lazyfree;
+
+	/* Refuse an anonymous range with no sign of use */
+	bool anon_require_referenced;
+
+	/* Map the PMD over a file collapse instead of leaving it to a fault */
+	bool file_install_pmd;
+
+	/* Write dirty pages back and retry once instead of refusing them */
+	bool file_writeback_dirty;
+
+	/* How hard to try for a destination folio */
+	gfp_t gfp;
+
+	/* Which VMAs are eligible, as thp_vma_allowable_orders() spells it */
+	enum tva_type tva_type;
+};
+
+struct collapse_control {
+	struct collapse_policy policy;
+
+	/* Num pages scanned per node */
+	u32 node_load[MAX_NUMNODES];
+
+	/* Num pages scanned (see khugepaged_pages_to_scan) */
+	unsigned int progress;
+
+	/* nodemask for allocation fallback */
+	nodemask_t alloc_nmask;
+
+	/* Each bit marks a PTE the scan accepted as a collapse source */
+	DECLARE_BITMAP(eligible_ptes, MAX_PTRS_PER_PTE);
+
+	/*
+	 * What a scan found and the collapse after it needs.  Live only between
+	 * the two, and read by nobody else.
+	 */
+
+	/* Anonymous only: orders to try, referenced and swap PTE counts */
+	unsigned long scan_orders;
+	int scan_referenced;
+	int scan_unmapped;
+
+	/*
+	 * File only.  A file collapse works on the page cache and never sees a
+	 * VMA, so the scan takes a reference to the file while it still has
+	 * one, and the collapse gives it back.
+	 */
+	struct file *scan_file;
+	pgoff_t scan_pgoff;
+};
+
+#endif	/* __MM_COLLAPSE_H */
diff --git a/mm/khugepaged.c b/mm/khugepaged.c
index dbae78b68dd85..ef5cd6fda34f7 100644
--- a/mm/khugepaged.c
+++ b/mm/khugepaged.c
@@ -26,44 +26,10 @@
 #include <linux/cleanup.h>
 
 #include <asm/tlb.h>
+#include "collapse.h"
 #include "internal.h"
-#include "page_alloc.h"
 #include "mm_slot.h"
-
-enum scan_result {
-	SCAN_FAIL,
-	SCAN_SUCCEED,
-	SCAN_NO_PTE_TABLE,
-	SCAN_PMD_MAPPED,
-	SCAN_EXCEED_NONE_PTE,
-	SCAN_EXCEED_SWAP_PTE,
-	SCAN_EXCEED_SHARED_PTE,
-	SCAN_PTE_NON_PRESENT,
-	SCAN_PTE_UFFD,
-	SCAN_PTE_MAPPED_HUGEPAGE,
-	SCAN_LACK_REFERENCED_PAGE,
-	SCAN_PAGE_NULL,
-	SCAN_SCAN_ABORT,
-	SCAN_PAGE_COUNT,
-	SCAN_PAGE_LRU,
-	SCAN_PAGE_LOCK,
-	SCAN_PAGE_ANON,
-	SCAN_PAGE_LAZYFREE,
-	SCAN_PAGE_COMPOUND,
-	SCAN_ANY_PROCESS,
-	SCAN_VMA_NULL,
-	SCAN_VMA_CHECK,
-	SCAN_ADDRESS_RANGE,
-	SCAN_DEL_PAGE_LRU,
-	SCAN_ALLOC_HUGE_PAGE_FAIL,
-	SCAN_CGROUP_CHARGE_FAIL,
-	SCAN_TRUNCATED,
-	SCAN_PAGE_HAS_PRIVATE,
-	SCAN_STORE_FAILED,
-	SCAN_COPY_MC,
-	SCAN_PAGE_FILLED,
-	SCAN_PAGE_DIRTY_OR_WRITEBACK,
-};
+#include "page_alloc.h"
 
 #define CREATE_TRACE_POINTS
 #include <trace/events/huge_memory.h>
@@ -91,7 +57,6 @@ static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
  *
  * Note that these are only respected if collapse was initiated by khugepaged.
  */
-#define KHUGEPAGED_MAX_PTES_LIMIT (HPAGE_PMD_NR - 1)
 unsigned int khugepaged_max_ptes_none __read_mostly;
 static unsigned int khugepaged_max_ptes_swap __read_mostly;
 static unsigned int khugepaged_max_ptes_shared __read_mostly;
@@ -101,24 +66,6 @@ static DEFINE_READ_MOSTLY_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
 
 static struct kmem_cache *mm_slot_cache __ro_after_init;
 
-#define KHUGEPAGED_MIN_MTHP_ORDER	2
-
-struct collapse_control {
-	bool is_khugepaged;
-
-	/* Num pages scanned per node */
-	u32 node_load[MAX_NUMNODES];
-
-	/* Num pages scanned (see khugepaged_pages_to_scan) */
-	unsigned int progress;
-
-	/* nodemask for allocation fallback */
-	nodemask_t alloc_nmask;
-
-	/* Each bit represents a single occupied (!none/zero) page. */
-	DECLARE_BITMAP(mthp_present_ptes, MAX_PTRS_PER_PTE);
-};
-
 /**
  * struct khugepaged_scan - cursor for scanning
  * @mm_head: the head of the mm list to scan
@@ -267,7 +214,7 @@ static ssize_t max_ptes_none_store(struct kobject *kobj,
 	unsigned long max_ptes_none;
 
 	err = kstrtoul(buf, 10, &max_ptes_none);
-	if (err || max_ptes_none > KHUGEPAGED_MAX_PTES_LIMIT)
+	if (err || max_ptes_none > COLLAPSE_MAX_PTES_LIMIT)
 		return -EINVAL;
 
 	khugepaged_max_ptes_none = max_ptes_none;
@@ -292,7 +239,7 @@ static ssize_t max_ptes_swap_store(struct kobject *kobj,
 	unsigned long max_ptes_swap;
 
 	err  = kstrtoul(buf, 10, &max_ptes_swap);
-	if (err || max_ptes_swap > KHUGEPAGED_MAX_PTES_LIMIT)
+	if (err || max_ptes_swap > COLLAPSE_MAX_PTES_LIMIT)
 		return -EINVAL;
 
 	khugepaged_max_ptes_swap = max_ptes_swap;
@@ -318,7 +265,7 @@ static ssize_t max_ptes_shared_store(struct kobject *kobj,
 	unsigned long max_ptes_shared;
 
 	err  = kstrtoul(buf, 10, &max_ptes_shared);
-	if (err || max_ptes_shared > KHUGEPAGED_MAX_PTES_LIMIT)
+	if (err || max_ptes_shared > COLLAPSE_MAX_PTES_LIMIT)
 		return -EINVAL;
 
 	khugepaged_max_ptes_shared = max_ptes_shared;
@@ -367,30 +314,17 @@ static bool pte_none_or_zero(pte_t pte)
 static unsigned int collapse_max_ptes_none(struct collapse_control *cc,
 		struct vm_area_struct *vma, unsigned int order)
 {
-	const unsigned int max_ptes_none = khugepaged_max_ptes_none;
+	unsigned int max_ptes_none;
 
 	if (vma && userfaultfd_armed(vma))
 		return 0;
-	/* for MADV_COLLAPSE, allow any empty/shared zeropage PTEs */
-	if (!cc->is_khugepaged)
-		return HPAGE_PMD_NR;
-	/* for PMD collapse, respect the user defined maximum */
 	if (is_pmd_order(order))
-		return max_ptes_none;
-	/*
-	 * for mTHP collapse with the sysctl value set to KHUGEPAGED_MAX_PTES_LIMIT,
-	 * scale the maximum number of PTEs to the order of the collapse.
-	 */
-	if (max_ptes_none == KHUGEPAGED_MAX_PTES_LIMIT)
+		return cc->policy.pmd.max_ptes_none;
+
+	/* Below PMD order: all but one PTE of the window, or none */
+	max_ptes_none = cc->policy.sub_pmd.max_ptes_none;
+	if (max_ptes_none == COLLAPSE_MAX_PTES_LIMIT)
 		return (1 << order) - 1;
-	/*
-	 * For mTHP collapse of values other than 0 or KHUGEPAGED_MAX_PTES_LIMIT,
-	 * emit a warning and return 0.
-	 */
-	if (max_ptes_none)
-		pr_warn_once("mTHP collapse does not support max_ptes_none"
-		     " values other than 0 or %u, defaulting to 0.\n",
-		     KHUGEPAGED_MAX_PTES_LIMIT);
 	return 0;
 }
 
@@ -406,20 +340,9 @@ static unsigned int collapse_max_ptes_none(struct collapse_control *cc,
 static unsigned int collapse_max_ptes_shared(struct collapse_control *cc,
 		unsigned int order)
 {
-	/*
-	 * For MADV_COLLAPSE, do not restrict the number of PTEs that map shared
-	 * anonymous pages.
-	 */
-	if (!cc->is_khugepaged)
-		return HPAGE_PMD_NR;
-	/*
-	 * for mTHP collapse do not allow collapsing anonymous memory pages that
-	 * are shared between processes.
-	 */
-	if (!is_pmd_order(order))
-		return 0;
-	/* for PMD collapse, respect the user defined maximum */
-	return khugepaged_max_ptes_shared;
+	if (is_pmd_order(order))
+		return cc->policy.pmd.max_ptes_shared;
+	return cc->policy.sub_pmd.max_ptes_shared;
 }
 
 /**
@@ -434,17 +357,9 @@ static unsigned int collapse_max_ptes_shared(struct collapse_control *cc,
 static unsigned int collapse_max_ptes_swap(struct collapse_control *cc,
 		unsigned int order)
 {
-	/*
-	 * For MADV_COLLAPSE, do not restrict the number PTEs entries or
-	 * pagecache entries that are non-present.
-	 */
-	if (!cc->is_khugepaged)
-		return HPAGE_PMD_NR;
-	/* for mTHP collapse do not allow any non-present PTEs or pagecache entries */
-	if (!is_pmd_order(order))
-		return 0;
-	/* for PMD collapse, respect the user defined maximum */
-	return khugepaged_max_ptes_swap;
+	if (is_pmd_order(order))
+		return cc->policy.pmd.max_ptes_swap;
+	return cc->policy.sub_pmd.max_ptes_swap;
 }
 
 int hugepage_madvise(struct vm_area_struct *vma,
@@ -476,7 +391,7 @@ int __init khugepaged_init(void)
 		return -ENOMEM;
 
 	khugepaged_pages_to_scan = HPAGE_PMD_NR * 8;
-	khugepaged_max_ptes_none = KHUGEPAGED_MAX_PTES_LIMIT;
+	khugepaged_max_ptes_none = COLLAPSE_MAX_PTES_LIMIT;
 	khugepaged_max_ptes_swap = HPAGE_PMD_NR / 8;
 	khugepaged_max_ptes_shared = HPAGE_PMD_NR / 2;
 
@@ -579,17 +494,11 @@ static unsigned long collapse_possible_orders(struct vm_area_struct *vma,
 	return thp_vma_allowable_orders(vma, vm_flags, tva_flags, orders);
 }
 
-static bool collapse_possible(struct vm_area_struct *vma,
-		vm_flags_t vm_flags, enum tva_type tva_flags)
-{
-	return collapse_possible_orders(vma, vm_flags, tva_flags);
-}
-
 void khugepaged_enter_vma(struct vm_area_struct *vma,
 			  vm_flags_t vm_flags)
 {
-	if (!mm_flags_test(MMF_VM_HUGEPAGE, vma->vm_mm) && hugepage_enabled()
-	    && collapse_possible(vma, vm_flags, TVA_KHUGEPAGED))
+	if (!mm_flags_test(MMF_VM_HUGEPAGE, vma->vm_mm) && hugepage_enabled() &&
+	    collapse_possible_orders(vma, vm_flags, TVA_KHUGEPAGED))
 		__khugepaged_enter(vma->vm_mm);
 }
 
@@ -623,11 +532,11 @@ void __khugepaged_exit(struct mm_struct *mm)
 	}
 }
 
-static void collapse_control_init_scan(struct collapse_control *cc)
+static void collapse_scan_reset(struct collapse_control *cc)
 {
 	memset(cc->node_load, 0, sizeof(cc->node_load));
 	nodes_clear(cc->alloc_nmask);
-	bitmap_zero(cc->mthp_present_ptes, MAX_PTRS_PER_PTE);
+	bitmap_zero(cc->eligible_ptes, MAX_PTRS_PER_PTE);
 }
 
 static void release_pte_folio(struct folio *folio)
@@ -731,13 +640,13 @@ static enum scan_result __collapse_huge_page_isolate(struct vm_area_struct *vma,
 		 * If the vma has the VM_DROPPABLE flag, the collapse will
 		 * preserve the lazyfree property without needing to skip.
 		 */
-		if (cc->is_khugepaged && !(vma->vm_flags & VM_DROPPABLE) &&
+		if (cc->policy.anon_skip_lazyfree && !(vma->vm_flags & VM_DROPPABLE) &&
 		    folio_test_lazyfree(folio) && !pte_dirty(pteval)) {
 			result = SCAN_PAGE_LAZYFREE;
 			goto out;
 		}
 
-		/* See collapse_scan_pmd(). */
+		/* See collapse_scan_anon(). */
 		if (folio_maybe_mapped_shared(folio)) {
 			/*
 			 * TODO: Support shared pages without leading to further
@@ -820,12 +729,12 @@ static enum scan_result __collapse_huge_page_isolate(struct vm_area_struct *vma,
 		if (folio_test_large(folio))
 			list_add_tail(&folio->lru, compound_pagelist);
 next:
-		if (cc->is_khugepaged &&
+		if (cc->policy.anon_require_referenced &&
 		    folio_pte_referenced(folio, vma, addr, pteval))
 			referenced++;
 	}
 
-	if (unlikely(cc->is_khugepaged && !referenced)) {
+	if (unlikely(cc->policy.anon_require_referenced && !referenced)) {
 		result = SCAN_LACK_REFERENCED_PAGE;
 	} else {
 		result = SCAN_SUCCEED;
@@ -991,9 +900,7 @@ static void khugepaged_alloc_sleep(void)
 	remove_wait_queue(&khugepaged_wait, &wait);
 }
 
-static struct collapse_control khugepaged_collapse_control = {
-	.is_khugepaged = true,
-};
+static struct collapse_control khugepaged_collapse_control;
 
 static bool collapse_scan_abort(int nid, struct collapse_control *cc)
 {
@@ -1029,6 +936,52 @@ static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)
 	return khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT;
 }
 
+/* khugepaged collapses on its own initiative, so it obeys its own settings */
+static void collapse_policy_khugepaged(struct collapse_policy *p)
+{
+	p->pmd.max_ptes_none = READ_ONCE(khugepaged_max_ptes_none);
+	p->pmd.max_ptes_swap = READ_ONCE(khugepaged_max_ptes_swap);
+	p->pmd.max_ptes_shared = READ_ONCE(khugepaged_max_ptes_shared);
+
+	/*
+	 * A sub-PMD window takes no swapped-out and no shared PTE: reading
+	 * pages back or breaking CoW is not worth it for an mTHP.  Empty PTEs
+	 * it takes all or nothing, since anything in between would let one
+	 * collapse feed the next.
+	 */
+	p->sub_pmd.max_ptes_none = p->pmd.max_ptes_none;
+	if (p->sub_pmd.max_ptes_none &&
+	    p->sub_pmd.max_ptes_none != COLLAPSE_MAX_PTES_LIMIT)
+		pr_warn_once("mTHP collapse does not support max_ptes_none values other than 0 or %u, defaulting to 0.\n",
+			     COLLAPSE_MAX_PTES_LIMIT);
+	p->sub_pmd.max_ptes_swap = 0;
+	p->sub_pmd.max_ptes_shared = 0;
+
+	p->anon_skip_lazyfree = true;
+	p->anon_require_referenced = true;
+	p->file_install_pmd = false;
+	p->file_writeback_dirty = false;
+	p->gfp = alloc_hugepage_khugepaged_gfpmask();
+	p->tva_type = TVA_KHUGEPAGED;
+}
+
+/* MADV_COLLAPSE was asked for explicitly, so it is not held to those */
+static void collapse_policy_madvise(struct collapse_policy *p)
+{
+	p->pmd.max_ptes_none = HPAGE_PMD_NR;
+	p->pmd.max_ptes_swap = HPAGE_PMD_NR;
+	p->pmd.max_ptes_shared = HPAGE_PMD_NR;
+	/* Never read: MADV_COLLAPSE collapses to PMD order only */
+	p->sub_pmd = p->pmd;
+
+	p->anon_skip_lazyfree = false;
+	p->anon_require_referenced = false;
+	p->file_install_pmd = true;
+	p->file_writeback_dirty = true;
+	p->gfp = GFP_TRANSHUGE;
+	p->tva_type = TVA_FORCED_COLLAPSE;
+}
+
 #ifdef CONFIG_NUMA
 static int collapse_find_target_node(struct collapse_control *cc)
 {
@@ -1066,8 +1019,7 @@ static enum scan_result hugepage_vma_revalidate(struct mm_struct *mm, unsigned l
 		struct collapse_control *cc, unsigned int order)
 {
 	struct vm_area_struct *vma;
-	enum tva_type type = cc->is_khugepaged ? TVA_KHUGEPAGED :
-				 TVA_FORCED_COLLAPSE;
+	enum tva_type type = cc->policy.tva_type;
 
 	if (unlikely(collapse_test_exit_or_disable(mm)))
 		return SCAN_ANY_PROCESS;
@@ -1147,7 +1099,7 @@ static enum scan_result check_pmd_still_valid(struct mm_struct *mm,
 
 /*
  * Bring missing pages in from swap, to complete THP collapse.
- * Only done if collapse_scan_pmd() believes it is worthwhile.
+ * Only done if collapse_scan_anon() believes it is worthwhile.
  *
  * For mTHP orders the function bails on the first swap entry, because
  * faulting pages back in during collapse could re-populate PTEs that
@@ -1250,8 +1202,7 @@ static enum scan_result __collapse_huge_page_swapin(struct mm_struct *mm,
 static enum scan_result alloc_charge_folio(struct folio **foliop, struct mm_struct *mm,
 		struct collapse_control *cc, unsigned int order)
 {
-	gfp_t gfp = (cc->is_khugepaged ? alloc_hugepage_khugepaged_gfpmask() :
-		     GFP_TRANSHUGE);
+	gfp_t gfp = cc->policy.gfp;
 	int node = collapse_find_target_node(cc);
 	struct folio *folio;
 
@@ -1301,8 +1252,8 @@ static pgtable_t alloc_deposit_pte_table(struct mm_struct *mm)
  * while allocating a THP, as that could trigger direct reclaim/compaction.
  * Note that the VMA must be rechecked after grabbing the mmap_lock again.
  */
-static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long start_addr,
-		int referenced, int unmapped, struct collapse_control *cc,
+static enum scan_result collapse_huge_page(struct mm_struct *mm,
+		unsigned long start_addr, struct collapse_control *cc,
 		unsigned int order)
 {
 	const unsigned long pmd_addr = start_addr & HPAGE_PMD_MASK;
@@ -1349,14 +1300,14 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long s
 		goto out_nolock;
 	}
 
-	if (unmapped) {
+	if (cc->scan_unmapped) {
 		/*
 		 * __collapse_huge_page_swapin() will return with mmap_lock
 		 * released when it fails. So we jump out_nolock directly in
 		 * that case.  Continuing to collapse causes inconsistency.
 		 */
 		result = __collapse_huge_page_swapin(mm, vma, start_addr, pmd,
-						     referenced, order);
+						     cc->scan_referenced, order);
 		if (result != SCAN_SUCCEED)
 			goto out_nolock;
 	}
@@ -1509,27 +1460,26 @@ static unsigned int max_order_from_offset(unsigned int offset)
 }
 
 /*
- * mthp_collapse() consumes the bitmap that is generated during
- * collapse_scan_pmd() to determine what regions and mTHP orders fit best.
+ * collapse_anon() consumes the bitmap that is generated during
+ * collapse_scan_anon() to determine what regions and mTHP orders fit best.
  *
- * Each bit in cc->mthp_present_ptes represents a single occupied (!none/zero)
- * page. We start at the PMD order and check if it is eligible for collapse;
+ * Each bit in cc->eligible_ptes marks a PTE the scan accepted as a collapse
+ * source. We start at the PMD order and check if it is eligible for collapse;
  * if not, we check the left and right halves of the PTE page table we are
  * examining at a lower order.
  *
- * For each of these, we determine how many PTE entries are occupied in the
- * range of PTE entries we propose to collapse, then we compare this to a
- * threshold number of PTE entries which would need to be occupied for a
- * collapse to be permitted at that order (accounting for max_ptes_none).
+ * For each of these, we count the eligible PTEs in the range we propose to
+ * collapse, then we compare this to the number of eligible PTEs the range
+ * would need for a collapse to be permitted at that order (accounting for
+ * max_ptes_none).
  *
  * If a collapse is permitted, we attempt to collapse the PTE range into a
  * mTHP.
  */
-static enum scan_result mthp_collapse(struct mm_struct *mm,
-		unsigned long address, int referenced, int unmapped,
-		struct collapse_control *cc, unsigned long enabled_orders)
+static enum scan_result collapse_anon(struct mm_struct *mm,
+		unsigned long address, struct collapse_control *cc)
 {
-	unsigned int nr_occupied_ptes, nr_ptes, max_ptes_none;
+	unsigned int nr_eligible_ptes, nr_ptes, max_ptes_none;
 	enum scan_result last_result = SCAN_FAIL;
 	int collapsed = 0;
 	bool alloc_failed = false;
@@ -1540,27 +1490,26 @@ static enum scan_result mthp_collapse(struct mm_struct *mm,
 	while (offset < HPAGE_PMD_NR) {
 		nr_ptes = 1UL << order;
 
-		if (!test_bit(order, &enabled_orders))
+		if (!test_bit(order, &cc->scan_orders))
 			goto next_order;
 
 		max_ptes_none = collapse_max_ptes_none(cc, NULL, order);
-		nr_occupied_ptes = bitmap_weight_from(cc->mthp_present_ptes, offset,
+		nr_eligible_ptes = bitmap_weight_from(cc->eligible_ptes, offset,
 						      offset + nr_ptes);
 
 		/*
-		 * Swap PTEs accepted during the scan are counted in @unmapped,
-		 * not in the present-PTE bitmap. Account them for the PMD-order
-		 * candidate.
+		 * Swap PTEs accepted during the scan are counted in
+		 * cc->scan_unmapped, not in cc->eligible_ptes. Account them for
+		 * the PMD-order candidate.
 		 */
 		if (is_pmd_order(order))
-			nr_occupied_ptes += unmapped;
+			nr_eligible_ptes += cc->scan_unmapped;
 
-		if (nr_occupied_ptes >= nr_ptes - max_ptes_none) {
+		if (nr_eligible_ptes >= nr_ptes - max_ptes_none) {
 			enum scan_result ret;
 
 			collapse_address = address + offset * PAGE_SIZE;
-			ret = collapse_huge_page(mm, collapse_address, referenced,
-						 unmapped, cc, order);
+			ret = collapse_huge_page(mm, collapse_address, cc, order);
 
 			switch (ret) {
 			/* Cases where we continue to next collapse candidate */
@@ -1601,8 +1550,8 @@ static enum scan_result mthp_collapse(struct mm_struct *mm,
 		 * any smaller order enabled. When at the smallest order
 		 * we must always move to the next offset.
 		 */
-		if (order > KHUGEPAGED_MIN_MTHP_ORDER &&
-			(enabled_orders & GENMASK(order - 1, 0))) {
+		if (order > COLLAPSE_MIN_MTHP_ORDER &&
+		    (cc->scan_orders & GENMASK(order - 1, 0))) {
 			order--;
 			continue;
 		}
@@ -1627,14 +1576,14 @@ static enum scan_result mthp_collapse(struct mm_struct *mm,
 	return last_result;
 }
 
-static enum scan_result collapse_scan_pmd(struct mm_struct *mm,
-		struct vm_area_struct *vma, unsigned long start_addr,
-		bool *lock_dropped, struct collapse_control *cc)
+static enum scan_result collapse_scan_anon(struct vm_area_struct *vma,
+		unsigned long start_addr, struct collapse_control *cc)
 {
 	const unsigned int max_ptes_shared = collapse_max_ptes_shared(cc, HPAGE_PMD_ORDER);
 	const unsigned int max_ptes_swap = collapse_max_ptes_swap(cc, HPAGE_PMD_ORDER);
 	unsigned int max_ptes_none = collapse_max_ptes_none(cc, vma, HPAGE_PMD_ORDER);
-	enum tva_type tva_flags = cc->is_khugepaged ? TVA_KHUGEPAGED : TVA_FORCED_COLLAPSE;
+	enum tva_type tva_flags = cc->policy.tva_type;
+	struct mm_struct *mm = vma->vm_mm;
 	pmd_t *pmd;
 	pte_t *pte, *_pte, pteval;
 	int i;
@@ -1656,17 +1605,17 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,
 		goto out;
 	}
 
-	collapse_control_init_scan(cc);
+	collapse_scan_reset(cc);
 
 	enabled_orders = collapse_possible_orders(vma, vma->vm_flags, tva_flags);
 
 	/*
 	 * If PMD is the only enabled order, enforce max_ptes_none, otherwise
 	 * scan all pages to populate the bitmap for mTHP collapse. The bitmap
-	 * is then checked again in mthp_collapse() for each attempted order.
+	 * is then checked again in collapse_anon() for each attempted order.
 	 */
 	if (enabled_orders != BIT(HPAGE_PMD_ORDER))
-		max_ptes_none = KHUGEPAGED_MAX_PTES_LIMIT;
+		max_ptes_none = COLLAPSE_MAX_PTES_LIMIT;
 
 	pte = pte_offset_map_lock(mm, pmd, start_addr, &ptl);
 	if (!pte) {
@@ -1734,7 +1683,7 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,
 		 * If the vma has the VM_DROPPABLE flag, the collapse will
 		 * preserve the lazyfree property without needing to skip.
 		 */
-		if (cc->is_khugepaged && !(vma->vm_flags & VM_DROPPABLE) &&
+		if (cc->policy.anon_skip_lazyfree && !(vma->vm_flags & VM_DROPPABLE) &&
 		    folio_test_lazyfree(folio) && !pte_dirty(pteval)) {
 			result = SCAN_PAGE_LAZYFREE;
 			failed_pfn = folio_pfn(folio);
@@ -1761,8 +1710,8 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,
 			}
 		}
 
-		/* Set bit for occupied pages */
-		__set_bit(i, cc->mthp_present_ptes);
+		/* The scan accepted this PTE as a collapse source */
+		__set_bit(i, cc->eligible_ptes);
 		/*
 		 * Record which node the original page is from and save this
 		 * information to cc->node_load[].
@@ -1800,13 +1749,13 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,
 			goto out_unmap;
 		}
 
-		if (cc->is_khugepaged &&
+		if (cc->policy.anon_require_referenced &&
 		    folio_pte_referenced(folio, vma, addr, pteval))
 			referenced++;
 	}
-	if (cc->is_khugepaged &&
-		   (!referenced ||
-		    (unmapped && referenced < HPAGE_PMD_NR / 2))) {
+	if (cc->policy.anon_require_referenced &&
+	    (!referenced ||
+	     (unmapped && referenced < HPAGE_PMD_NR / 2))) {
 		result = SCAN_LACK_REFERENCED_PAGE;
 	} else {
 		result = SCAN_SUCCEED;
@@ -1814,12 +1763,9 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,
 out_unmap:
 	pte_unmap_unlock(pte, ptl);
 	if (result == SCAN_SUCCEED) {
-		/* collapse_huge_page() expects the lock to be dropped before calling */
-		mmap_read_unlock(mm);
-		result = mthp_collapse(mm, start_addr, referenced,
-				       unmapped, cc, enabled_orders);
-		/* mmap_lock was released above, set lock_dropped */
-		*lock_dropped = true;
+		cc->scan_orders = enabled_orders;
+		cc->scan_referenced = referenced;
+		cc->scan_unmapped = unmapped;
 	}
 out:
 	trace_mm_khugepaged_scan_pmd(mm, failed_pfn, referenced,
@@ -2665,11 +2611,11 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
 	xas_unlock_irq(&xas);
 
 	/*
-	 * Remove pte page tables, so we can re-fault the page as huge.
-	 * If MADV_COLLAPSE, adjust result to call try_collapse_pte_mapped_thp().
+	 * Remove pte page tables, so we can re-fault the page as huge.  A
+	 * caller that wants the PMD mapped now is told to go and do that.
 	 */
 	retract_page_tables(mapping, start);
-	if (cc && !cc->is_khugepaged)
+	if (cc->policy.file_install_pmd)
 		result = SCAN_PTE_MAPPED_HUGEPAGE;
 	folio_unlock(new_folio);
 
@@ -2734,7 +2680,7 @@ static enum scan_result collapse_scan_file(struct mm_struct *mm,
 
 	present = 0;
 	swap = 0;
-	collapse_control_init_scan(cc);
+	collapse_scan_reset(cc);
 	rcu_read_lock();
 	xas_for_each(&xas, folio, start + HPAGE_PMD_NR - 1) {
 		if (xas_retry(&xas, folio))
@@ -2816,53 +2762,78 @@ static enum scan_result collapse_scan_file(struct mm_struct *mm,
 	else
 		cc->progress += HPAGE_PMD_NR;
 
-	if (result == SCAN_SUCCEED) {
-		if (present < HPAGE_PMD_NR - max_ptes_none) {
-			result = SCAN_EXCEED_NONE_PTE;
-			count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
-		} else {
-			result = collapse_file(mm, addr, file, start, cc);
-		}
+	if (result == SCAN_SUCCEED && present < HPAGE_PMD_NR - max_ptes_none) {
+		result = SCAN_EXCEED_NONE_PTE;
+		count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
 	}
 
-	trace_mm_khugepaged_scan_file(mm, failed_pfn, file, present, swap, result);
+	trace_mm_khugepaged_scan_file(mm, failed_pfn, file, present, swap,
+				      result);
 	return result;
 }
 
-/*
- * Try to collapse a single PMD starting at a PMD aligned addr, and return
- * the results.
- */
-static enum scan_result collapse_single_pmd(unsigned long addr,
-		struct vm_area_struct *vma, bool *lock_dropped,
-		struct collapse_control *cc)
+static void collapse_control_init(struct collapse_control *cc)
+{
+	cc->progress = 0;
+	cc->scan_file = NULL;
+}
+
+static enum scan_result collapse_scan_pmd(struct vm_area_struct *vma,
+		unsigned long addr, struct collapse_control *cc)
 {
-	struct mm_struct *mm = vma->vm_mm;
-	bool triggered_wb = false;
 	enum scan_result result;
-	struct file *file;
 	pgoff_t pgoff;
 
-	mmap_assert_locked(mm);
-
-	if (vma_is_anonymous(vma)) {
-		result = collapse_scan_pmd(mm, vma, addr, lock_dropped, cc);
-		goto end;
+	mmap_assert_locked(vma->vm_mm);
+	/* A scan that found work has to have been followed by collapse_pmd() */
+	if (WARN_ON_ONCE(cc->scan_file)) {
+		fput(cc->scan_file);
+		cc->scan_file = NULL;
 	}
 
-	file = get_file(vma->vm_file);
-	pgoff = linear_page_index(vma, addr);
+	if (vma_is_anonymous(vma))
+		return collapse_scan_anon(vma, addr, cc);
 
-	mmap_read_unlock(mm);
-	*lock_dropped = true;
-retry:
-	result = collapse_scan_file(mm, addr, file, pgoff, cc);
+	pgoff = linear_page_index(vma, addr);
+	result = collapse_scan_file(vma->vm_mm, addr, vma->vm_file, pgoff, cc);
+	/*
+	 * SCAN_PTE_MAPPED_HUGEPAGE is work too: the page cache already holds
+	 * the PMD folio, and collapse_pmd() still has to retract the PTE table.
+	 */
+	if (result != SCAN_SUCCEED && result != SCAN_PTE_MAPPED_HUGEPAGE)
+		return result;
 
 	/*
-	 * For MADV_COLLAPSE, when encountering dirty pages, try to writeback,
-	 * then retry the collapse one time.
+	 * A file collapse works on the page cache and never sees a VMA, so take
+	 * what it needs from this one while it is still here.
 	 */
-	if (!cc->is_khugepaged && result == SCAN_PAGE_DIRTY_OR_WRITEBACK &&
+	cc->scan_file = get_file(vma->vm_file);
+	cc->scan_pgoff = pgoff;
+	return result;
+}
+
+static enum scan_result collapse_pmd(struct mm_struct *mm,
+		unsigned long addr, enum scan_result result,
+		struct collapse_control *cc)
+{
+	struct file *file = cc->scan_file;
+	bool triggered_wb = false;
+	pgoff_t pgoff;
+
+	if (!file)
+		return collapse_anon(mm, addr, cc);
+
+	cc->scan_file = NULL;
+	pgoff = cc->scan_pgoff;
+
+	/* The scan found the PMD folio in place: nothing to collapse */
+	if (result == SCAN_PTE_MAPPED_HUGEPAGE)
+		goto put;
+retry:
+	result = collapse_file(mm, addr, file, pgoff, cc);
+
+	/* Dirty pages are worth a writeback and one more try, if asked for */
+	if (cc->policy.file_writeback_dirty && result == SCAN_PAGE_DIRTY_OR_WRITEBACK &&
 	    !triggered_wb && mapping_can_writeback(file->f_mapping)) {
 		const loff_t lstart = (loff_t)pgoff << PAGE_SHIFT;
 		const loff_t lend = lstart + HPAGE_PMD_SIZE - 1;
@@ -2871,25 +2842,49 @@ static enum scan_result collapse_single_pmd(unsigned long addr,
 		triggered_wb = true;
 		goto retry;
 	}
+put:
 	fput(file);
 
+	/*
+	 * A PMD folio is in the page cache, whether the collapse just put it
+	 * there or found it: retract the PTE table, and map the PMD if asked.
+	 */
 	if (result == SCAN_PTE_MAPPED_HUGEPAGE) {
 		mmap_read_lock(mm);
 		if (collapse_test_exit_or_disable(mm))
 			result = SCAN_ANY_PROCESS;
 		else
 			result = try_collapse_pte_mapped_thp(mm, addr,
-							     !cc->is_khugepaged);
+							cc->policy.file_install_pmd);
 		if (result == SCAN_PMD_MAPPED)
 			result = SCAN_SUCCEED;
 		mmap_read_unlock(mm);
 	}
-end:
-	if (cc->is_khugepaged && result == SCAN_SUCCEED)
-		++khugepaged_pages_collapsed;
 	return result;
 }
 
+/*
+ * Try to collapse a single PMD starting at a PMD aligned addr, and return
+ * the results.
+ */
+static enum scan_result collapse_single_pmd(unsigned long addr,
+		struct vm_area_struct *vma, bool *lock_dropped,
+		struct collapse_control *cc)
+{
+	struct mm_struct *mm = vma->vm_mm;
+	enum scan_result result;
+
+	result = collapse_scan_pmd(vma, addr, cc);
+	if (result != SCAN_SUCCEED && result != SCAN_PTE_MAPPED_HUGEPAGE)
+		return result;
+
+	/* The collapse takes its own locks, so give this up */
+	mmap_read_unlock(mm);
+	*lock_dropped = true;
+
+	return collapse_pmd(mm, addr, result, cc);
+}
+
 static void collapse_scan_mm_slot(unsigned int progress_max,
 		enum scan_result *result, struct collapse_control *cc)
 	__releases(&khugepaged_mm_lock)
@@ -2936,7 +2931,8 @@ static void collapse_scan_mm_slot(unsigned int progress_max,
 			cc->progress++;
 			break;
 		}
-		if (!collapse_possible(vma, vma->vm_flags, TVA_KHUGEPAGED)) {
+		if (!collapse_possible_orders(vma, vma->vm_flags,
+					      TVA_KHUGEPAGED)) {
 			cc->progress++;
 			continue;
 		}
@@ -2963,6 +2959,8 @@ static void collapse_scan_mm_slot(unsigned int progress_max,
 
 			*result = collapse_single_pmd(khugepaged_scan.address,
 						      vma, &lock_dropped, cc);
+			if (*result == SCAN_SUCCEED)
+				khugepaged_pages_collapsed++;
 			/* move to next address */
 			khugepaged_scan.address += HPAGE_PMD_SIZE;
 			if (lock_dropped)
@@ -3029,7 +3027,9 @@ static void khugepaged_do_scan(struct collapse_control *cc)
 
 	lru_add_drain_all();
 
-	cc->progress = 0;
+	collapse_control_init(cc);
+	collapse_policy_khugepaged(&cc->policy);
+
 	while (true) {
 		cond_resched();
 
@@ -3244,7 +3244,7 @@ int madvise_collapse(struct vm_area_struct *vma, unsigned long start,
 	BUG_ON(vma->vm_start > start);
 	BUG_ON(vma->vm_end < end);
 
-	if (!collapse_possible(vma, vma->vm_flags, TVA_FORCED_COLLAPSE))
+	if (!collapse_possible_orders(vma, vma->vm_flags, TVA_FORCED_COLLAPSE))
 		return -EINVAL;
 
 	hstart = ALIGN(start, HPAGE_PMD_SIZE);
@@ -3256,10 +3256,9 @@ int madvise_collapse(struct vm_area_struct *vma, unsigned long start,
 	cc = kmalloc_obj(*cc);
 	if (!cc)
 		return -ENOMEM;
-	cc->is_khugepaged = false;
-	cc->progress = 0;
+	collapse_control_init(cc);
+	collapse_policy_madvise(&cc->policy);
 
-	mmgrab(mm);
 	lru_add_drain_all();
 
 	for (addr = hstart; addr < hend; addr += HPAGE_PMD_SIZE) {
@@ -3315,7 +3314,6 @@ int madvise_collapse(struct vm_area_struct *vma, unsigned long start,
 	}
 out_nolock:
 	mmap_assert_locked(mm);
-	mmdrop(mm);
 	kfree(cc);
 
 	return thps == ((hend - hstart) >> HPAGE_PMD_SHIFT) ? 0

3/2 2026/10/14 23:14 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 15622
							output: 31
							thoughts: 1003
						

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

Okay, let's break this down. This patch is definitely one that needs a closer look, especially from a fuzzing perspective. It touches `MAINTAINERS`, a new header file `mm/collapse.h`, and, significantly, `mm/khugepaged.c`. My initial scan shows that it's refactoring the collapse control and policy, splitting the scan and collapse phases, and messing with reference counting – specifically, removing `mmgrab` and `mmdrop` calls, introducing an `fput` call and the `WARN_ON_ONCE` in `collapse_scan_pmd`.

The introduction of `mm/collapse.h` with those new data structures is a strong indicator that the underlying logic is being significantly changed. The way `cc->is_khugepaged` is being replaced with `cc->policy` suggests a generalization or, at least, a modification of the collapse control strategy. The split of `collapse_single_pmd` into `collapse_scan_pmd` and `collapse_pmd`, combined with the renaming, signals a re-architecting of the memory collapse process.

The removal of the `mmgrab` and `mmdrop` calls in `madvise_collapse` is particularly concerning. I need to understand *why* this was done. Was it intentional refactoring to optimize, or is it a subtle change that could have unintended consequences regarding memory management and locking? This warrants deeper investigation.

The introduction of `WARN_ON_ONCE` within `collapse_scan_pmd` is also a red flag. As a core memory management change, it's definitely reachable code that introduces a new runtime assertion. This kind of defensive check is ripe for fuzzing. The `if (WARN_ON_ONCE(cc->scan_file))` logic has me questioning what this check is trying to ensure and if any scenarios could trigger a violation of the newly introduced invariant.

Considering the specific points in the guidelines:

*   This is clearly core memory management code (`mm/`).
*   It's a significant restructuring and refactoring of memory collapse logic.
*   It introduces a new runtime assertion (`WARN_ON_ONCE`).

All of these points scream for fuzzing. This code is reachable via `madvise(..., MADV_COLLAPSE)` and the `khugepaged` kernel thread, meaning that any misstep could lead to memory corruption or other critical issues. The modifications regarding mmgrab/mmdrop, refactoring and new `WARN_ON_ONCE` further suggest that the patch potentially introduces new bugs.

Therefore, my assessment is that `WorthFuzzing` is unequivocally `true`. Now, I need to figure out the right `FocusSymbols` and `EnableConfigs` to tailor the fuzzing campaign effectively. I'll use `grepper` or `read-file` to get the necessary config and symbol details.



4/2 2026/10/14 23:14 tool grepper
0m Args:
{
  "Expression": "TRANSPARENT_HUGEPAGE",
  "PathPrefixes": [
    "mm/"
  ]
}

Results:
{
  "Output": "\nFull output is too long, showing 200 out of 907 lines.\nUse more precise expression or PathPrefixes if possible.\n\nNumber of matching lines per file (35 files in total):\nmm/Kconfig:24\nmm/Makefile:1\nmm/char-mem.c:1\nmm/compaction.c:1\nmm/damon/ops-common.c:4\nmm/damon/vaddr.c:7\nmm/debug_vm_pgtable.c:22\nmm/filemap.c:1\nmm/gup.c:2\nmm/hmm.c:4\nmm/huge_memory.c:35\nmm/khugepaged.c:3\nmm/ksm.c:1\nmm/madvise.c:2\nmm/mapping_dirty_helpers.c:1\nmm/memcontrol-v1.c:2\nmm/memcontrol.c:2\nmm/memory-failure.c:1\nmm/memory.c:17\nmm/mempolicy.c:1\nmm/migrate.c:1\nmm/mmap.c:1\nmm/mremap.c:3\nmm/page_alloc.c:3\nmm/page_idle.c:1\nmm/page_io.c:1\nmm/page_vma_mapped.c:2\nmm/pgtable-generic.c:3\nmm/rmap.c:9\nmm/shmem.c:32\nmm/show_mem.c:2\nmm/userfaultfd.c:1\nmm/util.c:1\nmm/vmscan.c:1\nmm/vmstat.c:2\n\nmm/Kconfig=815=config PERSISTENT_HUGE_ZERO_FOLIO\nmm/Kconfig-816-\tbool \"Allocate a PMD sized folio for zeroing\"\nmm/Kconfig:817:\tdepends on TRANSPARENT_HUGEPAGE\nmm/Kconfig-818-\thelp\n--\nmm/Kconfig=831=config MM_ID\n--\nmm/Kconfig-833-\nmm/Kconfig:834:menuconfig TRANSPARENT_HUGEPAGE\nmm/Kconfig-835-\tbool \"Transparent Hugepage Support\"\nmm/Kconfig:836:\tdepends on HAVE_ARCH_TRANSPARENT_HUGEPAGE \u0026\u0026 !PREEMPT_RT\nmm/Kconfig-837-\tselect COMPACTION\n--\nmm/Kconfig-849-\nmm/Kconfig:850:if TRANSPARENT_HUGEPAGE\nmm/Kconfig-851-\nmm/Kconfig=852=choice\nmm/Kconfig-853-\tprompt \"Transparent Hugepage Support sysfs defaults\"\nmm/Kconfig:854:\tdefault TRANSPARENT_HUGEPAGE_ALWAYS\nmm/Kconfig-855-\thelp\n--\nmm/Kconfig-857-\nmm/Kconfig:858:\tconfig TRANSPARENT_HUGEPAGE_ALWAYS\nmm/Kconfig-859-\t\tbool \"always\"\n--\nmm/Kconfig-864-\nmm/Kconfig:865:\tconfig TRANSPARENT_HUGEPAGE_MADVISE\nmm/Kconfig-866-\t\tbool \"madvise\"\n--\nmm/Kconfig-873-\nmm/Kconfig:874:\tconfig TRANSPARENT_HUGEPAGE_NEVER\nmm/Kconfig-875-\t\tbool \"never\"\n--\nmm/Kconfig=881=choice\nmm/Kconfig-882-\tprompt \"Shmem hugepage allocation defaults\"\nmm/Kconfig:883:\tdefault TRANSPARENT_HUGEPAGE_SHMEM_HUGE_NEVER\nmm/Kconfig-884-\thelp\n--\nmm/Kconfig-890-\nmm/Kconfig:891:\tconfig TRANSPARENT_HUGEPAGE_SHMEM_HUGE_NEVER\nmm/Kconfig-892-\t\tbool \"never\"\n--\nmm/Kconfig-900-\nmm/Kconfig:901:\tconfig TRANSPARENT_HUGEPAGE_SHMEM_HUGE_ALWAYS\nmm/Kconfig-902-\t\tbool \"always\"\n--\nmm/Kconfig-908-\nmm/Kconfig:909:\tconfig TRANSPARENT_HUGEPAGE_SHMEM_HUGE_WITHIN_SIZE\nmm/Kconfig-910-\t\tbool \"within_size\"\n--\nmm/Kconfig-916-\nmm/Kconfig:917:\tconfig TRANSPARENT_HUGEPAGE_SHMEM_HUGE_ADVISE\nmm/Kconfig-918-\t\tbool \"advise\"\n--\nmm/Kconfig=926=choice\nmm/Kconfig-927-\tprompt \"Tmpfs hugepage allocation defaults\"\nmm/Kconfig:928:\tdefault TRANSPARENT_HUGEPAGE_TMPFS_HUGE_NEVER\nmm/Kconfig-929-\thelp\n--\nmm/Kconfig-935-\nmm/Kconfig:936:\tconfig TRANSPARENT_HUGEPAGE_TMPFS_HUGE_NEVER\nmm/Kconfig-937-\t\tbool \"never\"\n--\nmm/Kconfig-944-\nmm/Kconfig:945:\tconfig TRANSPARENT_HUGEPAGE_TMPFS_HUGE_ALWAYS\nmm/Kconfig-946-\t\tbool \"always\"\n--\nmm/Kconfig-952-\nmm/Kconfig:953:\tconfig TRANSPARENT_HUGEPAGE_TMPFS_HUGE_WITHIN_SIZE\nmm/Kconfig-954-\t\tbool \"within_size\"\n--\nmm/Kconfig-960-\nmm/Kconfig:961:\tconfig TRANSPARENT_HUGEPAGE_TMPFS_HUGE_ADVISE\nmm/Kconfig-962-\t\tbool \"advise\"\n--\nmm/Kconfig=980=config NO_PAGE_MAPCOUNT\n--\nmm/Kconfig-992-\nmm/Kconfig:993:endif # TRANSPARENT_HUGEPAGE\nmm/Kconfig-994-\n--\nmm/Kconfig=1002=config PGTABLE_HAS_HUGE_LEAVES\nmm/Kconfig:1003:\tdef_bool TRANSPARENT_HUGEPAGE || HUGETLB_PAGE\nmm/Kconfig-1004-\n--\nmm/Kconfig=1008=config HAVE_GIGANTIC_FOLIOS\nmm/Kconfig-1009-\tdef_bool (HUGETLB_PAGE \u0026\u0026 ARCH_HAS_GIGANTIC_PAGE) || \\\nmm/Kconfig:1010:\t\t (ZONE_DEVICE \u0026\u0026 HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)\nmm/Kconfig-1011-\n--\nmm/Kconfig=1016=config ARCH_SUPPORTS_HUGE_PFNMAP\nmm/Kconfig-1017-\tdef_bool n\nmm/Kconfig:1018:\tdepends on TRANSPARENT_HUGEPAGE\nmm/Kconfig-1019-\nmm/Kconfig=1020=config ARCH_SUPPORTS_PMD_PFNMAP\nmm/Kconfig-1021-\tdef_bool y\nmm/Kconfig:1022:\tdepends on ARCH_SUPPORTS_HUGE_PFNMAP \u0026\u0026 HAVE_ARCH_TRANSPARENT_HUGEPAGE\nmm/Kconfig-1023-\nmm/Kconfig=1024=config ARCH_SUPPORTS_PUD_PFNMAP\nmm/Kconfig-1025-\tdef_bool y\nmm/Kconfig:1026:\tdepends on ARCH_SUPPORTS_HUGE_PFNMAP \u0026\u0026 HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD\nmm/Kconfig-1027-\n--\nmm/Makefile=101=obj-$(CONFIG_DEVICE_MIGRATION) += migrate_device.o\nmm/Makefile:102:obj-$(CONFIG_TRANSPARENT_HUGEPAGE) += huge_memory.o khugepaged.o\nmm/Makefile-103-obj-$(CONFIG_PAGE_COUNTER) += page_counter.o\n--\nmm/char-mem.c=523=static unsigned long get_unmapped_area_zero(struct file *file,\n--\nmm/char-mem.c-542-\t */\nmm/char-mem.c:543:#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/char-mem.c-544-\treturn thp_get_unmapped_area(file, addr, len, pgoff, flags);\n--\nmm/compaction.c=60=static inline bool is_via_compact_memory(int order) { return false; }\n--\nmm/compaction.c-75- */\nmm/compaction.c:76:#if defined CONFIG_TRANSPARENT_HUGEPAGE\nmm/compaction.c-77-#define COMPACTION_HPAGE_ORDER\tHPAGE_PMD_ORDER\n--\nmm/damon/ops-common.c=96=void damon_pmdp_mkold(pmd_t *pmd, struct vm_area_struct *vma, unsigned long addr)\nmm/damon/ops-common.c-97-{\nmm/damon/ops-common.c:98:#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/damon/ops-common.c-99-\tpmd_t pmdval = pmdp_get(pmd);\n--\nmm/damon/ops-common.c-120-\tfolio_put(folio);\nmm/damon/ops-common.c:121:#endif /* CONFIG_TRANSPARENT_HUGEPAGE */\nmm/damon/ops-common.c-122-}\n--\nmm/damon/ops-common.c=294=static bool damon_folio_young_one(struct folio *folio,\n--\nmm/damon/ops-common.c-310-\t\t} else {\nmm/damon/ops-common.c:311:#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/damon/ops-common.c-312-\t\t\tpmd_t pmd = pmdp_get(pvmw.pmd);\n--\nmm/damon/ops-common.c-318-\t\t\tWARN_ON_ONCE(1);\nmm/damon/ops-common.c:319:#endif\t/* CONFIG_TRANSPARENT_HUGEPAGE */\nmm/damon/ops-common.c-320-\t\t}\n--\nmm/damon/vaddr.c=352=static int damon_young_pmd_entry(pmd_t *pmd, unsigned long addr,\n--\nmm/damon/vaddr.c-360-\nmm/damon/vaddr.c:361:#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/damon/vaddr.c-362-\tptl = pmd_trans_huge_lock(pmd, walk-\u003evma);\n--\nmm/damon/vaddr.c-378-\t}\nmm/damon/vaddr.c:379:#endif\t/* CONFIG_TRANSPARENT_HUGEPAGE */\nmm/damon/vaddr.c-380-\n--\nmm/damon/vaddr.c=604=static int damon_va_probe_pmd_entry(pmd_t *pmd, unsigned long addr,\n--\nmm/damon/vaddr.c-612-\nmm/damon/vaddr.c:613:#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/damon/vaddr.c-614-\tptl = pmd_trans_huge_lock(pmd, walk-\u003evma);\n--\nmm/damon/vaddr.c-629-\t}\nmm/damon/vaddr.c:630:#endif\t/* CONFIG_TRANSPARENT_HUGEPAGE */\nmm/damon/vaddr.c-631-\n--\nmm/damon/vaddr.c=837=static int damos_va_migrate_pmd_entry(pmd_t *pmd, unsigned long addr,\n--\nmm/damon/vaddr.c-848-\nmm/damon/vaddr.c:849:#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/damon/vaddr.c-850-\tptl = pmd_trans_huge_lock(pmd, walk-\u003evma);\n--\nmm/damon/vaddr.c-866-\t}\nmm/damon/vaddr.c:867:#endif\t/* CONFIG_TRANSPARENT_HUGEPAGE */\nmm/damon/vaddr.c-868-\n--\nmm/damon/vaddr.c=1000=static int damos_va_stat_pmd_entry(pmd_t *pmd, unsigned long addr,\n--\nmm/damon/vaddr.c-1011-\nmm/damon/vaddr.c:1012:#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/damon/vaddr.c-1013-\tptl = pmd_trans_huge_lock(pmd, vma);\n--\nmm/debug_vm_pgtable.c=114=static void __init pte_advanced_tests(struct pgtable_debug_args *args)\n--\nmm/debug_vm_pgtable.c-172-\nmm/debug_vm_pgtable.c:173:#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/debug_vm_pgtable.c-174-static void __init pmd_basic_tests(struct pgtable_debug_args *args, int idx)\n--\nmm/debug_vm_pgtable.c=282=static void __init pmd_leaf_tests(struct pgtable_debug_args *args)\n--\nmm/debug_vm_pgtable.c-298-\nmm/debug_vm_pgtable.c:299:#ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD\nmm/debug_vm_pgtable.c-300-static void __init pud_basic_tests(struct pgtable_debug_args *args, int idx)\n--\nmm/debug_vm_pgtable.c=405=static void __init pud_leaf_tests(struct pgtable_debug_args *args)\n--\nmm/debug_vm_pgtable.c-419-}\nmm/debug_vm_pgtable.c:420:#else  /* !CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */\nmm/debug_vm_pgtable.c-421-static void __init pud_basic_tests(struct pgtable_debug_args *args, int idx) { }\n--\nmm/debug_vm_pgtable.c=423=static void __init pud_leaf_tests(struct pgtable_debug_args *args) { }\nmm/debug_vm_pgtable.c:424:#endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */\nmm/debug_vm_pgtable.c:425:#else  /* !CONFIG_TRANSPARENT_HUGEPAGE */\nmm/debug_vm_pgtable.c-426-static void __init pmd_basic_tests(struct pgtable_debug_args *args, int idx) { }\n--\nmm/debug_vm_pgtable.c=431=static void __init pud_leaf_tests(struct pgtable_debug_args *args) { }\nmm/debug_vm_pgtable.c:432:#endif /* CONFIG_TRANSPARENT_HUGEPAGE */\nmm/debug_vm_pgtable.c-433-\n\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 21183
							output: 37
							thoughts: 190
						

Thoughts:
**Analyzing the Transparent Hugepage Configuration**

Okay, so I see that `huge_memory.o` and `khugepaged.o` are going to be compiled if `CONFIG_TRANSPARENT_HUGEPAGE` is set. My initial thought is to confirm that this is the primary configuration option controlling the inclusion of `mm/khugepaged.c`. Let's dig into the `mm/Kconfig` file.

Right, here it is: `menuconfig TRANSPARENT_HUGEPAGE`. Seems straightforward enough. It's a boolean option, and it depends on `HAVE_ARCH_TRANSPARENT_HUGEPAGE` and excludes `PREEMPT_RT`. Good to know, and the `select COMPACTION` is useful context as well. So `TRANSPARENT_HUGEPAGE` is indeed the main trigger.

Now, the next step is to understand what's *in* `mm/khugepaged.c`. I need to identify what functions are new or modified within that file and then, critically, how those functions are called and integrated into the rest of the memory management system. Time to carefully inspect the diffs and then the code itself. This is where the real work begins.



6/2 2026/10/14 23:14 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 1460,
  "LineCount": 60
}

Results:
{
  "Contents": "1460:\t}\n1461:\t\n1462:\t/*\n1463:\t * collapse_anon() consumes the bitmap that is generated during\n1464:\t * collapse_scan_anon() to determine what regions and mTHP orders fit best.\n1465:\t *\n1466:\t * Each bit in cc-\u003eeligible_ptes marks a PTE the scan accepted as a collapse\n1467:\t * source. We start at the PMD order and check if it is eligible for collapse;\n1468:\t * if not, we check the left and right halves of the PTE page table we are\n1469:\t * examining at a lower order.\n1470:\t *\n1471:\t * For each of these, we count the eligible PTEs in the range we propose to\n1472:\t * collapse, then we compare this to the number of eligible PTEs the range\n1473:\t * would need for a collapse to be permitted at that order (accounting for\n1474:\t * max_ptes_none).\n1475:\t *\n1476:\t * If a collapse is permitted, we attempt to collapse the PTE range into a\n1477:\t * mTHP.\n1478:\t */\n1479:\tstatic enum scan_result collapse_anon(struct mm_struct *mm,\n1480:\t\t\tunsigned long address, struct collapse_control *cc)\n1481:\t{\n1482:\t\tunsigned int nr_eligible_ptes, nr_ptes, max_ptes_none;\n1483:\t\tenum scan_result last_result = SCAN_FAIL;\n1484:\t\tint collapsed = 0;\n1485:\t\tbool alloc_failed = false;\n1486:\t\tunsigned long collapse_address;\n1487:\t\tunsigned int offset = 0;\n1488:\t\tunsigned int order = HPAGE_PMD_ORDER;\n1489:\t\n1490:\t\twhile (offset \u003c HPAGE_PMD_NR) {\n1491:\t\t\tnr_ptes = 1UL \u003c\u003c order;\n1492:\t\n1493:\t\t\tif (!test_bit(order, \u0026cc-\u003escan_orders))\n1494:\t\t\t\tgoto next_order;\n1495:\t\n1496:\t\t\tmax_ptes_none = collapse_max_ptes_none(cc, NULL, order);\n1497:\t\t\tnr_eligible_ptes = bitmap_weight_from(cc-\u003eeligible_ptes, offset,\n1498:\t\t\t\t\t\t\t      offset + nr_ptes);\n1499:\t\n1500:\t\t\t/*\n1501:\t\t\t * Swap PTEs accepted during the scan are counted in\n1502:\t\t\t * cc-\u003escan_unmapped, not in cc-\u003eeligible_ptes. Account them for\n1503:\t\t\t * the PMD-order candidate.\n1504:\t\t\t */\n1505:\t\t\tif (is_pmd_order(order))\n1506:\t\t\t\tnr_eligible_ptes += cc-\u003escan_unmapped;\n1507:\t\n1508:\t\t\tif (nr_eligible_ptes \u003e= nr_ptes - max_ptes_none) {\n1509:\t\t\t\tenum scan_result ret;\n1510:\t\n1511:\t\t\t\tcollapse_address = address + offset * PAGE_SIZE;\n1512:\t\t\t\tret = collapse_huge_page(mm, collapse_address, cc, order);\n1513:\t\n1514:\t\t\t\tswitch (ret) {\n1515:\t\t\t\t/* Cases where we continue to next collapse candidate */\n1516:\t\t\t\tcase SCAN_SUCCEED:\n1517:\t\t\t\t\tcollapsed += nr_ptes;\n1518:\t\t\t\t\tfallthrough;\n1519:\t\t\t\tcase SCAN_PTE_MAPPED_HUGEPAGE:\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 22649
							output: 37
							thoughts: 67
						

Thoughts:
Here's my take on the thought process, as if it were my own:

**Analyzing Memory Collapse Functions**

Okay, so I need to get a really good understanding of this memory collapse logic. Let's see...I'm thinking I should start by mapping out all the functions involved in the collapse process. I need to make sure I don't miss anything that could impact the outcome of the analysis. So, let's start with those listed: `collapse_scan_anon`, `collapse_scan_pmd`, `collapse_pmd`, `collapse_single_pmd`, `madvise_collapse`, `collapse_scan_mm_slot`, and `khugepaged_do_scan`, and any others that seem relevant. I have to trace through their interactions and understand the specific role each one plays in bringing memory regions together.



8/2 2026/10/14 23:14 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 1570,
  "LineCount": 60
}

Results:
{
  "Contents": "1570:\t\t}\n1571:\tdone:\n1572:\t\tif (collapsed)\n1573:\t\t\treturn SCAN_SUCCEED;\n1574:\t\tif (alloc_failed)\n1575:\t\t\treturn SCAN_ALLOC_HUGE_PAGE_FAIL;\n1576:\t\treturn last_result;\n1577:\t}\n1578:\t\n1579:\tstatic enum scan_result collapse_scan_anon(struct vm_area_struct *vma,\n1580:\t\t\tunsigned long start_addr, struct collapse_control *cc)\n1581:\t{\n1582:\t\tconst unsigned int max_ptes_shared = collapse_max_ptes_shared(cc, HPAGE_PMD_ORDER);\n1583:\t\tconst unsigned int max_ptes_swap = collapse_max_ptes_swap(cc, HPAGE_PMD_ORDER);\n1584:\t\tunsigned int max_ptes_none = collapse_max_ptes_none(cc, vma, HPAGE_PMD_ORDER);\n1585:\t\tenum tva_type tva_flags = cc-\u003epolicy.tva_type;\n1586:\t\tstruct mm_struct *mm = vma-\u003evm_mm;\n1587:\t\tpmd_t *pmd;\n1588:\t\tpte_t *pte, *_pte, pteval;\n1589:\t\tint i;\n1590:\t\tint none_or_zero = 0, shared = 0, referenced = 0;\n1591:\t\tenum scan_result result = SCAN_FAIL;\n1592:\t\tstruct page *page = NULL;\n1593:\t\tstruct folio *folio = NULL;\n1594:\t\tunsigned long failed_pfn = -1;\n1595:\t\tunsigned long addr;\n1596:\t\tunsigned long enabled_orders;\n1597:\t\tspinlock_t *ptl;\n1598:\t\tint node = NUMA_NO_NODE, unmapped = 0;\n1599:\t\n1600:\t\tVM_BUG_ON(start_addr \u0026 ~HPAGE_PMD_MASK);\n1601:\t\n1602:\t\tresult = find_pmd_or_thp_or_none(mm, start_addr, \u0026pmd);\n1603:\t\tif (result != SCAN_SUCCEED) {\n1604:\t\t\tcc-\u003eprogress++;\n1605:\t\t\tgoto out;\n1606:\t\t}\n1607:\t\n1608:\t\tcollapse_scan_reset(cc);\n1609:\t\n1610:\t\tenabled_orders = collapse_possible_orders(vma, vma-\u003evm_flags, tva_flags);\n1611:\t\n1612:\t\t/*\n1613:\t\t * If PMD is the only enabled order, enforce max_ptes_none, otherwise\n1614:\t\t * scan all pages to populate the bitmap for mTHP collapse. The bitmap\n1615:\t\t * is then checked again in collapse_anon() for each attempted order.\n1616:\t\t */\n1617:\t\tif (enabled_orders != BIT(HPAGE_PMD_ORDER))\n1618:\t\t\tmax_ptes_none = COLLAPSE_MAX_PTES_LIMIT;\n1619:\t\n1620:\t\tpte = pte_offset_map_lock(mm, pmd, start_addr, \u0026ptl);\n1621:\t\tif (!pte) {\n1622:\t\t\tcc-\u003eprogress++;\n1623:\t\t\tresult = SCAN_NO_PTE_TABLE;\n1624:\t\t\tgoto out;\n1625:\t\t}\n1626:\t\n1627:\t\tfor (i = 0; i \u003c HPAGE_PMD_NR; i++) {\n1628:\t\t\t_pte = pte + i;\n1629:\t\t\taddr = start_addr + i * PAGE_SIZE;\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 23944
							output: 35
							thoughts: 23
						

Thoughts:
Okay, here's my thought process laid out, as if I were thinking it:

**Digging into Memory Management: A Quick Drill-Down**

Right, let's get down to brass tacks. I've got a hunch about something, and to confirm it, I need to focus my investigation. Specifically, I want to immediately zero in on a few key areas related to memory management. First, I need to know exactly *who* is calling `collapse_single_pmd`. This will give me a very specific view of how it's being used. I'm expecting this is happening a lot, as this is a core optimization. The context of its usage will tell me a lot about its role. Second, and related, I need to understand what's happening around `madvise` and, importantly, what interfaces with `khugepaged`. These are also key areas of investigation, as they deal directly with memory hints and automatic management, and are likely to interact. By cross-referencing these two areas, I can build up a mental model of the memory management landscape, and uncover what I'm looking for.



10/2 2026/10/14 23:14 tool grepper
0m Args:
{
  "Expression": "collapse_single_pmd|madvise_collapse",
  "PathPrefixes": [
    "mm/"
  ]
}

Results:
{
  "Output": "mm/khugepaged.c=2815=static enum scan_result collapse_pmd(struct mm_struct *mm,\n--\nmm/khugepaged.c-2869- */\nmm/khugepaged.c:2870:static enum scan_result collapse_single_pmd(unsigned long addr,\nmm/khugepaged.c-2871-\t\tstruct vm_area_struct *vma, bool *lock_dropped,\n--\nmm/khugepaged.c=2888=static void collapse_scan_mm_slot(unsigned int progress_max,\n--\nmm/khugepaged.c-2959-\nmm/khugepaged.c:2960:\t\t\t*result = collapse_single_pmd(khugepaged_scan.address,\nmm/khugepaged.c-2961-\t\t\t\t\t\t      vma, \u0026lock_dropped, cc);\n--\nmm/khugepaged.c=3197=bool current_is_khugepaged(void)\n--\nmm/khugepaged.c-3201-\nmm/khugepaged.c:3202:static int madvise_collapse_errno(enum scan_result r)\nmm/khugepaged.c-3203-{\n--\nmm/khugepaged.c-3233-\nmm/khugepaged.c:3234:int madvise_collapse(struct vm_area_struct *vma, unsigned long start,\nmm/khugepaged.c-3235-\t\t     unsigned long end, bool *lock_dropped)\n--\nmm/khugepaged.c-3281-\nmm/khugepaged.c:3282:\t\tresult = collapse_single_pmd(addr, vma, \u0026mmap_unlocked, cc);\nmm/khugepaged.c-3283-\n--\nmm/khugepaged.c-3319-\treturn thps == ((hend - hstart) \u003e\u003e HPAGE_PMD_SHIFT) ? 0\nmm/khugepaged.c:3320:\t\t\t: madvise_collapse_errno(last_fail);\nmm/khugepaged.c-3321-}\n--\nmm/madvise.c=1356=static int madvise_vma_behavior(struct madvise_behavior *madv_behavior)\n--\nmm/madvise.c-1380-\tcase MADV_COLLAPSE:\nmm/madvise.c:1381:\t\treturn madvise_collapse(vma, range-\u003estart, range-\u003eend,\nmm/madvise.c-1382-\t\t\t\u0026madv_behavior-\u003elock_dropped);\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 24922
							output: 44
							thoughts: 381
						

Thoughts:
**Analyzing the `madvise_collapse` Implementation**

Okay, let's break this down. It looks like `madvise_collapse` is the entry point, called when `madvise(..., MADV_COLLAPSE)` is used, and it funnels down through `madvise_vma_behavior`. From there, the flow seems to involve `khugepaged`, specifically, `collapse_scan_mm_slot` which is triggered by `khugepaged_scan_mm_slot` within the `khugepaged_do_scan` function, which in turn resides in the `khugepaged` kernel thread loop, `khugepaged_loop`.

Looking at `mm/khugepaged.c`, the scope of the patch is quite extensive, it touches a considerable number of functions and variables:  It affects the inner workings of the collapse policy, both the khugepaged and madvise approaches, initialization, and several scan and collapse related functions that are static.  In addition, functions dealing with VMA entry and madvise at the hugepage level are impacted. And it seems to expose several new sysfs handlers related to PTE limits for various store types, the patch seems to have a substantial impact.

Now, I need to get a better sense of how this fits into the overall picture. I should take a closer look at that `khugepaged_loop` to see how everything interacts. I need to understand the control flow.



12/2 2026/10/14 23:14 tool grepper
0m Args:
{
  "Expression": "khugepaged_loop|khugepaged_do_scan",
  "PathPrefixes": [
    "mm/khugepaged.c"
  ]
}

Results:
{
  "Output": "mm/khugepaged.c=3015=static int khugepaged_wait_event(void)\n--\nmm/khugepaged.c-3020-\nmm/khugepaged.c:3021:static void khugepaged_do_scan(struct collapse_control *cc)\nmm/khugepaged.c-3022-{\n--\nmm/khugepaged.c=3091=static int khugepaged(void *none)\n--\nmm/khugepaged.c-3098-\twhile (!kthread_should_stop()) {\nmm/khugepaged.c:3099:\t\tkhugepaged_do_scan(\u0026khugepaged_collapse_control);\nmm/khugepaged.c-3100-\t\tkhugepaged_wait_work();\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 25883
							output: 17
							thoughts: 1266
						

Thoughts:
**Focusing on THP Collapse in khugepaged**

Okay, so I'm diving into this `khugepaged` code and need to identify the key functions to target for fuzzing.  `khugepaged_do_scan` is the workhorse, called by `khugepaged`, the kthread, which is a key process here, so it's probably not *that* ubiquitous. `madvise_collapse` is a primary API entrypoint, definitely a good candidate.

Looking at the diff, it seems `collapse_possible()` was swapped out for `collapse_possible_orders()` in `khugepaged_enter_vma`. That's interesting, so `khugepaged_enter_vma` might be a relevant function to examine too.

Now, the instructions are clear: avoid the ubiquitous functions. Static inlines in headers are a no-go for symbol coverage, but substantial static functions *in .c files* are often distinct symbols. I need to make sure I am focused on the correct symbols here.

My target functions are:

*   `madvise_collapse`: The direct entrypoint, perfect.
*   `khugepaged_enter_vma`: For VMA registration.
*   `collapse_single_pmd`: Called by both `madvise_collapse` and `collapse_scan_mm_slot`.
*   `collapse_scan_pmd`: A newly factored scan function.
*   `collapse_pmd`: Another newly factored function executing the collapse.
*   `collapse_anon`: Renamed from `mthp_collapse` and modified.
*   `collapse_scan_anon`: Renamed from `collapse_scan_pmd` and modified.
*   `collapse_file`: Modified in handling `cc->policy.file_install_pmd`.
*   `collapse_scan_file`: Modified.
*   `collapse_huge_page`: Modified arguments and unmapped/referenced handling.
*   `khugepaged_do_scan`: The workhorse scanner function.

These all seem highly specific to the THP collapse logic and aren't core memory management or synchronization primitives. Excellent.

Finally, I need to check the scope of the changes.  A `git show --stat` reveals changes only to `MAINTAINERS`, `mm/collapse.h`, and `mm/khugepaged.c`. `mm/collapse.h` seems to contain definitions and the others are the actual implementation, so I am going to make sure that these are all the symbols.

I should be good to go. This set appears to give pretty good coverage of the change.



14/2 2026/10/14 23:14 tool grepper
0m Args:
{
  "Expression": "collapse\\.h"
}

Results:
{
  "Output": "MAINTAINERS=17454=F:\tinclude/trace/events/huge_memory.h\nMAINTAINERS:17455:F:\tmm/collapse.h\nMAINTAINERS-17456-F:\tmm/huge_memory.c\n--\nmm/khugepaged.c-28-#include \u003casm/tlb.h\u003e\nmm/khugepaged.c:29:#include \"collapse.h\"\nmm/khugepaged.c-30-#include \"internal.h\"\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 27887
							output: 39
							thoughts: 242
						

Thoughts:
**My Analysis of Transparent Hugepage Configuration**

Okay, so I'm digging into how transparent hugepages are configured in this kernel. First off, I see that the `khugepaged.c` file, the core of the functionality, is only included in a specific context. I need to figure out the exact configuration that enables it.

My initial thought is to check the `CONFIG_TRANSPARENT_HUGEPAGE` option. Looking at the `mm/Makefile`, I see the line `obj-$(CONFIG_TRANSPARENT_HUGEPAGE) += huge_memory.o khugepaged.o`. That confirms it: `TRANSPARENT_HUGEPAGE` is the key.

But, I know better than to stop there. I need to be thorough. Are there any dependencies or sub-configurations involved? I see `HAVE_ARCH_TRANSPARENT_HUGEPAGE`, which appears to be an architecture-specific config, likely selected by amd64/x86. Good to know, but doesn't seem to be a hard dependency.

Next, I'll consider the more granular options, specifically `CONFIG_TRANSPARENT_HUGEPAGE_ALWAYS` and `CONFIG_TRANSPARENT_HUGEPAGE_MADVISE`. Are they *required* or is `TRANSPARENT_HUGEPAGE` alone sufficient to get `khugepaged` running? It looks like `TRANSPARENT_HUGEPAGE` itself is a menuconfig option, and that *enables* compilation of `khugepaged.c`.

Finally, to be completely certain, I'll take a quick look inside `mm/khugepaged.c` itself. I'm checking for any `#ifdef CONFIG_` guards within the file, which would indicate any conditional compilation based on other configuration options. This will make certain I haven't missed a crucial detail.



16/2 2026/10/14 23:15 tool grepper
0m Args:
{
  "Expression": "CONFIG_",
  "PathPrefixes": [
    "mm/khugepaged.c",
    "mm/collapse.h"
  ]
}

Results:
{
  "Output": "mm/khugepaged.c=83=static struct khugepaged_scan khugepaged_scan = {\n--\nmm/khugepaged.c-86-\nmm/khugepaged.c:87:#ifdef CONFIG_SYSFS\nmm/khugepaged.c-88-static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,\n--\nmm/khugepaged.c=292=struct attribute_group khugepaged_attr_group = {\n--\nmm/khugepaged.c-295-};\nmm/khugepaged.c:296:#endif /* CONFIG_SYSFS */\nmm/khugepaged.c-297-\n--\nmm/khugepaged.c=969=static void collapse_policy_madvise(struct collapse_policy *p)\n--\nmm/khugepaged.c-984-\nmm/khugepaged.c:985:#ifdef CONFIG_NUMA\nmm/khugepaged.c-986-static int collapse_find_target_node(struct collapse_control *cc)\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 28866
							output: 257
							thoughts: 330
						

Thoughts:
**My Analysis of the `mm/khugepaged.c` Refactor**

Okay, so I'm looking at this patch and, as expected, it's primarily focused on `mm/khugepaged.c` and is tied to `NUMA` and the `SYSFS` configurations.  Right off the bat, I know that `TRANSPARENT_HUGEPAGE` is the config that's going to compile `khugepaged.o`, making it the key enabler here.

Let me just solidify the underlying logic:

This is marked as "WorthFuzzing" due to it being a critical section of the memory management subsystem. They're touching the transparent hugepage (THP) collapse infrastructure, specifically in `mm/khugepaged.c` and introducing `mm/collapse.h`. The refactoring is breaking down PMD collapse into scanning and collapsing phases, which is a good move for fine-grained control, and they're bringing in these `collapse_control` policies with limits. The separation of `khugepaged`'s background scanning from `MADV_COLLAPSE` also seems smart. They are also modifying reference counting, which is always an interesting and potentially risky area. And a new runtime assertion with `WARN_ON_ONCE(cc->scan_file)` is in place. It's accessible via `madvise(MADV_COLLAPSE)` and the `khugepaged` daemon as the documentation suggested.

The relevant symbols are:

*   `madvise_collapse`
*   `collapse_single_pmd`
*   `collapse_scan_pmd`
*   `collapse_pmd`
*   `collapse_anon`
*   `collapse_scan_anon`
*   `collapse_file`
*   `collapse_scan_file`
*   `khugepaged_do_scan`

And finally, `TRANSPARENT_HUGEPAGE` is the only config that's required to actually enable this functionality.

Based on everything I'm seeing, this is all clean, accurate, and completely lines up with the code changes. I'm satisfied. Let's call `set-results`.



18/2 2026/10/14 23:15 tool set-results
0m Args:
{
  "EnableConfigs": [
    "TRANSPARENT_HUGEPAGE"
  ],
  "FocusSymbols": [
    "madvise_collapse",
    "collapse_single_pmd",
    "collapse_scan_pmd",
    "collapse_pmd",
    "collapse_anon",
    "collapse_scan_anon",
    "collapse_file",
    "collapse_scan_file",
    "khugepaged_do_scan"
  ],
  "Reasoning": "The patch refactors transparent huge page (THP) collapse logic in mm/khugepaged.c and introduces mm/collapse.h. It decouples scan and collapse phases into separate functions (collapse_scan_pmd, collapse_scan_anon, collapse_pmd, collapse_anon), formalizes collapse policies/limits between background khugepaged and MADV_COLLAPSE, alters file reference handling (with a new WARN_ON_ONCE assertion checking cc-\u003escan_file), and modifies reference management in madvise_collapse. This reachable core memory management code is actively exercised via madvise(MADV_COLLAPSE) and the khugepaged kthread.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "TRANSPARENT_HUGEPAGE"
  ],
  "FocusSymbols": [
    "madvise_collapse",
    "collapse_single_pmd",
    "collapse_scan_pmd",
    "collapse_pmd",
    "collapse_anon",
    "collapse_scan_anon",
    "collapse_file",
    "collapse_scan_file",
    "khugepaged_do_scan"
  ],
  "Reasoning": "The patch refactors transparent huge page (THP) collapse logic in mm/khugepaged.c and introduces mm/collapse.h. It decouples scan and collapse phases into separate functions (collapse_scan_pmd, collapse_scan_anon, collapse_pmd, collapse_anon), formalizes collapse policies/limits between background khugepaged and MADV_COLLAPSE, alters file reference handling (with a new WARN_ON_ONCE assertion checking cc-\u003escan_file), and modifies reference management in madvise_collapse. This reachable core memory management code is actively exercised via madvise(MADV_COLLAPSE) and the khugepaged kthread.",
  "WorthFuzzing": true
}

19/1 2026/10/14 23:15 action If
2m Args:
{
  "WorthFuzzing": true
}

Results:
null

20/2 2026/10/14 23:15 agent kmsan-evaluator
2m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch series refactors the transparent hugepage (THP) collapse logic in mm/khugepaged.c by introducing struct collapse_policy and struct collapse_control in mm/collapse.h to encapsulate collapse configurations (khugepaged vs madvise) and state across scan and collapse phases.\n\nEvaluating against KMSAN criteria:\n1. No kernel structures or data are copied to user space (no copy_to_user, put_user, netlink, ioctl output, socket options, or BPF buffers).\n2. All fields in struct collapse_policy and struct collapse_control are explicitly initialized (via collapse_control_init(), collapse_policy_khugepaged(), collapse_policy_madvise(), collapse_scan_reset(), and during successful scan phases) prior to being read or used in conditional logic.\n3. No uninitialized memory usage or info-leak risks are introduced. Any potential bugs in this refactoring would pertain to page/folio reference counting, locking (mmap_lock / folio locks), or state-tracking logic, which are covered by KASAN, LOCKDEP, and standard kernel debugging facilities.\n\nTherefore, a dedicated KMSAN fuzzing session is not warranted.",
  "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 ff94c96f8aca60d916dea20b7f431378dd8e74b0
Author: syz-cluster <triage@syzkaller.com>
Date:   Wed Oct 14 23:14:02 2026 +0000

    syz-cluster: applied patch under review

diff --git a/MAINTAINERS b/MAINTAINERS
index 39abe7378b6fc..5c38da7090db8 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -17452,6 +17452,7 @@ F:	Documentation/admin-guide/mm/transhuge.rst
 F:	include/linux/huge_mm.h
 F:	include/linux/khugepaged.h
 F:	include/trace/events/huge_memory.h
+F:	mm/collapse.h
 F:	mm/huge_memory.c
 F:	mm/khugepaged.c
 F:	mm/mm_slot.h
diff --git a/mm/collapse.h b/mm/collapse.h
new file mode 100644
index 0000000000000..759ec9cd45414
--- /dev/null
+++ b/mm/collapse.h
@@ -0,0 +1,121 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __MM_COLLAPSE_H
+#define __MM_COLLAPSE_H
+
+#include <linux/mm.h>
+#include <linux/nodemask.h>
+#include <linux/pgtable.h>
+#include <linux/types.h>
+
+#define COLLAPSE_MAX_PTES_LIMIT		(HPAGE_PMD_NR - 1)
+#define COLLAPSE_MIN_MTHP_ORDER		2
+
+enum scan_result {
+	SCAN_FAIL,
+	SCAN_SUCCEED,
+	SCAN_NO_PTE_TABLE,
+	SCAN_PMD_MAPPED,
+	SCAN_EXCEED_NONE_PTE,
+	SCAN_EXCEED_SWAP_PTE,
+	SCAN_EXCEED_SHARED_PTE,
+	SCAN_PTE_NON_PRESENT,
+	SCAN_PTE_UFFD,
+	SCAN_PTE_MAPPED_HUGEPAGE,
+	SCAN_LACK_REFERENCED_PAGE,
+	SCAN_PAGE_NULL,
+	SCAN_SCAN_ABORT,
+	SCAN_PAGE_COUNT,
+	SCAN_PAGE_LRU,
+	SCAN_PAGE_LOCK,
+	SCAN_PAGE_ANON,
+	SCAN_PAGE_LAZYFREE,
+	SCAN_PAGE_COMPOUND,
+	SCAN_ANY_PROCESS,
+	SCAN_VMA_NULL,
+	SCAN_VMA_CHECK,
+	SCAN_ADDRESS_RANGE,
+	SCAN_DEL_PAGE_LRU,
+	SCAN_ALLOC_HUGE_PAGE_FAIL,
+	SCAN_CGROUP_CHARGE_FAIL,
+	SCAN_TRUNCATED,
+	SCAN_PAGE_HAS_PRIVATE,
+	SCAN_STORE_FAILED,
+	SCAN_COPY_MC,
+	SCAN_PAGE_FILLED,
+	SCAN_PAGE_DIRTY_OR_WRITEBACK,
+};
+
+/* How many PTEs of a window may be missing, swapped out or shared */
+struct collapse_limits {
+	/* Counted over a PMD-sized window; HPAGE_PMD_NR means "no limit" */
+	unsigned int max_ptes_none;
+	unsigned int max_ptes_swap;
+	unsigned int max_ptes_shared;
+};
+
+/* What a collapse is allowed to do, decided by the caller that asks for it */
+struct collapse_policy {
+	/* Limits for a PMD-sized window */
+	struct collapse_limits pmd;
+
+	/*
+	 * Limits for a smaller window.  Its max_ptes_none is either 0 or
+	 * COLLAPSE_MAX_PTES_LIMIT, the latter meaning all but one PTE of the
+	 * window whatever its order; any other value counts as 0.
+	 */
+	struct collapse_limits sub_pmd;
+
+	/* Leave clean lazyfree folios to reclaim rather than collapse them */
+	bool anon_skip_lazyfree;
+
+	/* Refuse an anonymous range with no sign of use */
+	bool anon_require_referenced;
+
+	/* Map the PMD over a file collapse instead of leaving it to a fault */
+	bool file_install_pmd;
+
+	/* Write dirty pages back and retry once instead of refusing them */
+	bool file_writeback_dirty;
+
+	/* How hard to try for a destination folio */
+	gfp_t gfp;
+
+	/* Which VMAs are eligible, as thp_vma_allowable_orders() spells it */
+	enum tva_type tva_type;
+};
+
+struct collapse_control {
+	struct collapse_policy policy;
+
+	/* Num pages scanned per node */
+	u32 node_load[MAX_NUMNODES];
+
+	/* Num pages scanned (see khugepaged_pages_to_scan) */
+	unsigned int progress;
+
+	/* nodemask for allocation fallback */
+	nodemask_t alloc_nmask;
+
+	/* Each bit marks a PTE the scan accepted as a collapse source */
+	DECLARE_BITMAP(eligible_ptes, MAX_PTRS_PER_PTE);
+
+	/*
+	 * What a scan found and the collapse after it needs.  Live only between
+	 * the two, and read by nobody else.
+	 */
+
+	/* Anonymous only: orders to try, referenced and swap PTE counts */
+	unsigned long scan_orders;
+	int scan_referenced;
+	int scan_unmapped;
+
+	/*
+	 * File only.  A file collapse works on the page cache and never sees a
+	 * VMA, so the scan takes a reference to the file while it still has
+	 * one, and the collapse gives it back.
+	 */
+	struct file *scan_file;
+	pgoff_t scan_pgoff;
+};
+
+#endif	/* __MM_COLLAPSE_H */
diff --git a/mm/khugepaged.c b/mm/khugepaged.c
index dbae78b68dd85..ef5cd6fda34f7 100644
--- a/mm/khugepaged.c
+++ b/mm/khugepaged.c
@@ -26,44 +26,10 @@
 #include <linux/cleanup.h>
 
 #include <asm/tlb.h>
+#include "collapse.h"
 #include "internal.h"
-#include "page_alloc.h"
 #include "mm_slot.h"
-
-enum scan_result {
-	SCAN_FAIL,
-	SCAN_SUCCEED,
-	SCAN_NO_PTE_TABLE,
-	SCAN_PMD_MAPPED,
-	SCAN_EXCEED_NONE_PTE,
-	SCAN_EXCEED_SWAP_PTE,
-	SCAN_EXCEED_SHARED_PTE,
-	SCAN_PTE_NON_PRESENT,
-	SCAN_PTE_UFFD,
-	SCAN_PTE_MAPPED_HUGEPAGE,
-	SCAN_LACK_REFERENCED_PAGE,
-	SCAN_PAGE_NULL,
-	SCAN_SCAN_ABORT,
-	SCAN_PAGE_COUNT,
-	SCAN_PAGE_LRU,
-	SCAN_PAGE_LOCK,
-	SCAN_PAGE_ANON,
-	SCAN_PAGE_LAZYFREE,
-	SCAN_PAGE_COMPOUND,
-	SCAN_ANY_PROCESS,
-	SCAN_VMA_NULL,
-	SCAN_VMA_CHECK,
-	SCAN_ADDRESS_RANGE,
-	SCAN_DEL_PAGE_LRU,
-	SCAN_ALLOC_HUGE_PAGE_FAIL,
-	SCAN_CGROUP_CHARGE_FAIL,
-	SCAN_TRUNCATED,
-	SCAN_PAGE_HAS_PRIVATE,
-	SCAN_STORE_FAILED,
-	SCAN_COPY_MC,
-	SCAN_PAGE_FILLED,
-	SCAN_PAGE_DIRTY_OR_WRITEBACK,
-};
+#include "page_alloc.h"
 
 #define CREATE_TRACE_POINTS
 #include <trace/events/huge_memory.h>
@@ -91,7 +57,6 @@ static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
  *
  * Note that these are only respected if collapse was initiated by khugepaged.
  */
-#define KHUGEPAGED_MAX_PTES_LIMIT (HPAGE_PMD_NR - 1)
 unsigned int khugepaged_max_ptes_none __read_mostly;
 static unsigned int khugepaged_max_ptes_swap __read_mostly;
 static unsigned int khugepaged_max_ptes_shared __read_mostly;
@@ -101,24 +66,6 @@ static DEFINE_READ_MOSTLY_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
 
 static struct kmem_cache *mm_slot_cache __ro_after_init;
 
-#define KHUGEPAGED_MIN_MTHP_ORDER	2
-
-struct collapse_control {
-	bool is_khugepaged;
-
-	/* Num pages scanned per node */
-	u32 node_load[MAX_NUMNODES];
-
-	/* Num pages scanned (see khugepaged_pages_to_scan) */
-	unsigned int progress;
-
-	/* nodemask for allocation fallback */
-	nodemask_t alloc_nmask;
-
-	/* Each bit represents a single occupied (!none/zero) page. */
-	DECLARE_BITMAP(mthp_present_ptes, MAX_PTRS_PER_PTE);
-};
-
 /**
  * struct khugepaged_scan - cursor for scanning
  * @mm_head: the head of the mm list to scan
@@ -267,7 +214,7 @@ static ssize_t max_ptes_none_store(struct kobject *kobj,
 	unsigned long max_ptes_none;
 
 	err = kstrtoul(buf, 10, &max_ptes_none);
-	if (err || max_ptes_none > KHUGEPAGED_MAX_PTES_LIMIT)
+	if (err || max_ptes_none > COLLAPSE_MAX_PTES_LIMIT)
 		return -EINVAL;
 
 	khugepaged_max_ptes_none = max_ptes_none;
@@ -292,7 +239,7 @@ static ssize_t max_ptes_swap_store(struct kobject *kobj,
 	unsigned long max_ptes_swap;
 
 	err  = kstrtoul(buf, 10, &max_ptes_swap);
-	if (err || max_ptes_swap > KHUGEPAGED_MAX_PTES_LIMIT)
+	if (err || max_ptes_swap > COLLAPSE_MAX_PTES_LIMIT)
 		return -EINVAL;
 
 	khugepaged_max_ptes_swap = max_ptes_swap;
@@ -318,7 +265,7 @@ static ssize_t max_ptes_shared_store(struct kobject *kobj,
 	unsigned long max_ptes_shared;
 
 	err  = kstrtoul(buf, 10, &max_ptes_shared);
-	if (err || max_ptes_shared > KHUGEPAGED_MAX_PTES_LIMIT)
+	if (err || max_ptes_shared > COLLAPSE_MAX_PTES_LIMIT)
 		return -EINVAL;
 
 	khugepaged_max_ptes_shared = max_ptes_shared;
@@ -367,30 +314,17 @@ static bool pte_none_or_zero(pte_t pte)
 static unsigned int collapse_max_ptes_none(struct collapse_control *cc,
 		struct vm_area_struct *vma, unsigned int order)
 {
-	const unsigned int max_ptes_none = khugepaged_max_ptes_none;
+	unsigned int max_ptes_none;
 
 	if (vma && userfaultfd_armed(vma))
 		return 0;
-	/* for MADV_COLLAPSE, allow any empty/shared zeropage PTEs */
-	if (!cc->is_khugepaged)
-		return HPAGE_PMD_NR;
-	/* for PMD collapse, respect the user defined maximum */
 	if (is_pmd_order(order))
-		return max_ptes_none;
-	/*
-	 * for mTHP collapse with the sysctl value set to KHUGEPAGED_MAX_PTES_LIMIT,
-	 * scale the maximum number of PTEs to the order of the collapse.
-	 */
-	if (max_ptes_none == KHUGEPAGED_MAX_PTES_LIMIT)
+		return cc->policy.pmd.max_ptes_none;
+
+	/* Below PMD order: all but one PTE of the window, or none */
+	max_ptes_none = cc->policy.sub_pmd.max_ptes_none;
+	if (max_ptes_none == COLLAPSE_MAX_PTES_LIMIT)
 		return (1 << order) - 1;
-	/*
-	 * For mTHP collapse of values other than 0 or KHUGEPAGED_MAX_PTES_LIMIT,
-	 * emit a warning and return 0.
-	 */
-	if (max_ptes_none)
-		pr_warn_once("mTHP collapse does not support max_ptes_none"
-		     " values other than 0 or %u, defaulting to 0.\n",
-		     KHUGEPAGED_MAX_PTES_LIMIT);
 	return 0;
 }
 
@@ -406,20 +340,9 @@ static unsigned int collapse_max_ptes_none(struct collapse_control *cc,
 static unsigned int collapse_max_ptes_shared(struct collapse_control *cc,
 		unsigned int order)
 {
-	/*
-	 * For MADV_COLLAPSE, do not restrict the number of PTEs that map shared
-	 * anonymous pages.
-	 */
-	if (!cc->is_khugepaged)
-		return HPAGE_PMD_NR;
-	/*
-	 * for mTHP collapse do not allow collapsing anonymous memory pages that
-	 * are shared between processes.
-	 */
-	if (!is_pmd_order(order))
-		return 0;
-	/* for PMD collapse, respect the user defined maximum */
-	return khugepaged_max_ptes_shared;
+	if (is_pmd_order(order))
+		return cc->policy.pmd.max_ptes_shared;
+	return cc->policy.sub_pmd.max_ptes_shared;
 }
 
 /**
@@ -434,17 +357,9 @@ static unsigned int collapse_max_ptes_shared(struct collapse_control *cc,
 static unsigned int collapse_max_ptes_swap(struct collapse_control *cc,
 		unsigned int order)
 {
-	/*
-	 * For MADV_COLLAPSE, do not restrict the number PTEs entries or
-	 * pagecache entries that are non-present.
-	 */
-	if (!cc->is_khugepaged)
-		return HPAGE_PMD_NR;
-	/* for mTHP collapse do not allow any non-present PTEs or pagecache entries */
-	if (!is_pmd_order(order))
-		return 0;
-	/* for PMD collapse, respect the user defined maximum */
-	return khugepaged_max_ptes_swap;
+	if (is_pmd_order(order))
+		return cc->policy.pmd.max_ptes_swap;
+	return cc->policy.sub_pmd.max_ptes_swap;
 }
 
 int hugepage_madvise(struct vm_area_struct *vma,
@@ -476,7 +391,7 @@ int __init khugepaged_init(void)
 		return -ENOMEM;
 
 	khugepaged_pages_to_scan = HPAGE_PMD_NR * 8;
-	khugepaged_max_ptes_none = KHUGEPAGED_MAX_PTES_LIMIT;
+	khugepaged_max_ptes_none = COLLAPSE_MAX_PTES_LIMIT;
 	khugepaged_max_ptes_swap = HPAGE_PMD_NR / 8;
 	khugepaged_max_ptes_shared = HPAGE_PMD_NR / 2;
 
@@ -579,17 +494,11 @@ static unsigned long collapse_possible_orders(struct vm_area_struct *vma,
 	return thp_vma_allowable_orders(vma, vm_flags, tva_flags, orders);
 }
 
-static bool collapse_possible(struct vm_area_struct *vma,
-		vm_flags_t vm_flags, enum tva_type tva_flags)
-{
-	return collapse_possible_orders(vma, vm_flags, tva_flags);
-}
-
 void khugepaged_enter_vma(struct vm_area_struct *vma,
 			  vm_flags_t vm_flags)
 {
-	if (!mm_flags_test(MMF_VM_HUGEPAGE, vma->vm_mm) && hugepage_enabled()
-	    && collapse_possible(vma, vm_flags, TVA_KHUGEPAGED))
+	if (!mm_flags_test(MMF_VM_HUGEPAGE, vma->vm_mm) && hugepage_enabled() &&
+	    collapse_possible_orders(vma, vm_flags, TVA_KHUGEPAGED))
 		__khugepaged_enter(vma->vm_mm);
 }
 
@@ -623,11 +532,11 @@ void __khugepaged_exit(struct mm_struct *mm)
 	}
 }
 
-static void collapse_control_init_scan(struct collapse_control *cc)
+static void collapse_scan_reset(struct collapse_control *cc)
 {
 	memset(cc->node_load, 0, sizeof(cc->node_load));
 	nodes_clear(cc->alloc_nmask);
-	bitmap_zero(cc->mthp_present_ptes, MAX_PTRS_PER_PTE);
+	bitmap_zero(cc->eligible_ptes, MAX_PTRS_PER_PTE);
 }
 
 static void release_pte_folio(struct folio *folio)
@@ -731,13 +640,13 @@ static enum scan_result __collapse_huge_page_isolate(struct vm_area_struct *vma,
 		 * If the vma has the VM_DROPPABLE flag, the collapse will
 		 * preserve the lazyfree property without needing to skip.
 		 */
-		if (cc->is_khugepaged && !(vma->vm_flags & VM_DROPPABLE) &&
+		if (cc->policy.anon_skip_lazyfree && !(vma->vm_flags & VM_DROPPABLE) &&
 		    folio_test_lazyfree(folio) && !pte_dirty(pteval)) {
 			result = SCAN_PAGE_LAZYFREE;
 			goto out;
 		}
 
-		/* See collapse_scan_pmd(). */
+		/* See collapse_scan_anon(). */
 		if (folio_maybe_mapped_shared(folio)) {
 			/*
 			 * TODO: Support shared pages without leading to further
@@ -820,12 +729,12 @@ static enum scan_result __collapse_huge_page_isolate(struct vm_area_struct *vma,
 		if (folio_test_large(folio))
 			list_add_tail(&folio->lru, compound_pagelist);
 next:
-		if (cc->is_khugepaged &&
+		if (cc->policy.anon_require_referenced &&
 		    folio_pte_referenced(folio, vma, addr, pteval))
 			referenced++;
 	}
 
-	if (unlikely(cc->is_khugepaged && !referenced)) {
+	if (unlikely(cc->policy.anon_require_referenced && !referenced)) {
 		result = SCAN_LACK_REFERENCED_PAGE;
 	} else {
 		result = SCAN_SUCCEED;
@@ -991,9 +900,7 @@ static void khugepaged_alloc_sleep(void)
 	remove_wait_queue(&khugepaged_wait, &wait);
 }
 
-static struct collapse_control khugepaged_collapse_control = {
-	.is_khugepaged = true,
-};
+static struct collapse_control khugepaged_collapse_control;
 
 static bool collapse_scan_abort(int nid, struct collapse_control *cc)
 {
@@ -1029,6 +936,52 @@ static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)
 	return khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT;
 }
 
+/* khugepaged collapses on its own initiative, so it obeys its own settings */
+static void collapse_policy_khugepaged(struct collapse_policy *p)
+{
+	p->pmd.max_ptes_none = READ_ONCE(khugepaged_max_ptes_none);
+	p->pmd.max_ptes_swap = READ_ONCE(khugepaged_max_ptes_swap);
+	p->pmd.max_ptes_shared = READ_ONCE(khugepaged_max_ptes_shared);
+
+	/*
+	 * A sub-PMD window takes no swapped-out and no shared PTE: reading
+	 * pages back or breaking CoW is not worth it for an mTHP.  Empty PTEs
+	 * it takes all or nothing, since anything in between would let one
+	 * collapse feed the next.
+	 */
+	p->sub_pmd.max_ptes_none = p->pmd.max_ptes_none;
+	if (p->sub_pmd.max_ptes_none &&
+	    p->sub_pmd.max_ptes_none != COLLAPSE_MAX_PTES_LIMIT)
+		pr_warn_once("mTHP collapse does not support max_ptes_none values other than 0 or %u, defaulting to 0.\n",
+			     COLLAPSE_MAX_PTES_LIMIT);
+	p->sub_pmd.max_ptes_swap = 0;
+	p->sub_pmd.max_ptes_shared = 0;
+
+	p->anon_skip_lazyfree = true;
+	p->anon_require_referenced = true;
+	p->file_install_pmd = false;
+	p->file_writeback_dirty = false;
+	p->gfp = alloc_hugepage_khugepaged_gfpmask();
+	p->tva_type = TVA_KHUGEPAGED;
+}
+
+/* MADV_COLLAPSE was asked for explicitly, so it is not held to those */
+static void collapse_policy_madvise(struct collapse_policy *p)
+{
+	p->pmd.max_ptes_none = HPAGE_PMD_NR;
+	p->pmd.max_ptes_swap = HPAGE_PMD_NR;
+	p->pmd.max_ptes_shared = HPAGE_PMD_NR;
+	/* Never read: MADV_COLLAPSE collapses to PMD order only */
+	p->sub_pmd = p->pmd;
+
+	p->anon_skip_lazyfree = false;
+	p->anon_require_referenced = false;
+	p->file_install_pmd = true;
+	p->file_writeback_dirty = true;
+	p->gfp = GFP_TRANSHUGE;
+	p->tva_type = TVA_FORCED_COLLAPSE;
+}
+
 #ifdef CONFIG_NUMA
 static int collapse_find_target_node(struct collapse_control *cc)
 {
@@ -1066,8 +1019,7 @@ static enum scan_result hugepage_vma_revalidate(struct mm_struct *mm, unsigned l
 		struct collapse_control *cc, unsigned int order)
 {
 	struct vm_area_struct *vma;
-	enum tva_type type = cc->is_khugepaged ? TVA_KHUGEPAGED :
-				 TVA_FORCED_COLLAPSE;
+	enum tva_type type = cc->policy.tva_type;
 
 	if (unlikely(collapse_test_exit_or_disable(mm)))
 		return SCAN_ANY_PROCESS;
@@ -1147,7 +1099,7 @@ static enum scan_result check_pmd_still_valid(struct mm_struct *mm,
 
 /*
  * Bring missing pages in from swap, to complete THP collapse.
- * Only done if collapse_scan_pmd() believes it is worthwhile.
+ * Only done if collapse_scan_anon() believes it is worthwhile.
  *
  * For mTHP orders the function bails on the first swap entry, because
  * faulting pages back in during collapse could re-populate PTEs that
@@ -1250,8 +1202,7 @@ static enum scan_result __collapse_huge_page_swapin(struct mm_struct *mm,
 static enum scan_result alloc_charge_folio(struct folio **foliop, struct mm_struct *mm,
 		struct collapse_control *cc, unsigned int order)
 {
-	gfp_t gfp = (cc->is_khugepaged ? alloc_hugepage_khugepaged_gfpmask() :
-		     GFP_TRANSHUGE);
+	gfp_t gfp = cc->policy.gfp;
 	int node = collapse_find_target_node(cc);
 	struct folio *folio;
 
@@ -1301,8 +1252,8 @@ static pgtable_t alloc_deposit_pte_table(struct mm_struct *mm)
  * while allocating a THP, as that could trigger direct reclaim/compaction.
  * Note that the VMA must be rechecked after grabbing the mmap_lock again.
  */
-static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long start_addr,
-		int referenced, int unmapped, struct collapse_control *cc,
+static enum scan_result collapse_huge_page(struct mm_struct *mm,
+		unsigned long start_addr, struct collapse_control *cc,
 		unsigned int order)
 {
 	const unsigned long pmd_addr = start_addr & HPAGE_PMD_MASK;
@@ -1349,14 +1300,14 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long s
 		goto out_nolock;
 	}
 
-	if (unmapped) {
+	if (cc->scan_unmapped) {
 		/*
 		 * __collapse_huge_page_swapin() will return with mmap_lock
 		 * released when it fails. So we jump out_nolock directly in
 		 * that case.  Continuing to collapse causes inconsistency.
 		 */
 		result = __collapse_huge_page_swapin(mm, vma, start_addr, pmd,
-						     referenced, order);
+						     cc->scan_referenced, order);
 		if (result != SCAN_SUCCEED)
 			goto out_nolock;
 	}
@@ -1509,27 +1460,26 @@ static unsigned int max_order_from_offset(unsigned int offset)
 }
 
 /*
- * mthp_collapse() consumes the bitmap that is generated during
- * collapse_scan_pmd() to determine what regions and mTHP orders fit best.
+ * collapse_anon() consumes the bitmap that is generated during
+ * collapse_scan_anon() to determine what regions and mTHP orders fit best.
  *
- * Each bit in cc->mthp_present_ptes represents a single occupied (!none/zero)
- * page. We start at the PMD order and check if it is eligible for collapse;
+ * Each bit in cc->eligible_ptes marks a PTE the scan accepted as a collapse
+ * source. We start at the PMD order and check if it is eligible for collapse;
  * if not, we check the left and right halves of the PTE page table we are
  * examining at a lower order.
  *
- * For each of these, we determine how many PTE entries are occupied in the
- * range of PTE entries we propose to collapse, then we compare this to a
- * threshold number of PTE entries which would need to be occupied for a
- * collapse to be permitted at that order (accounting for max_ptes_none).
+ * For each of these, we count the eligible PTEs in the range we propose to
+ * collapse, then we compare this to the number of eligible PTEs the range
+ * would need for a collapse to be permitted at that order (accounting for
+ * max_ptes_none).
  *
  * If a collapse is permitted, we attempt to collapse the PTE range into a
  * mTHP.
  */
-static enum scan_result mthp_collapse(struct mm_struct *mm,
-		unsigned long address, int referenced, int unmapped,
-		struct collapse_control *cc, unsigned long enabled_orders)
+static enum scan_result collapse_anon(struct mm_struct *mm,
+		unsigned long address, struct collapse_control *cc)
 {
-	unsigned int nr_occupied_ptes, nr_ptes, max_ptes_none;
+	unsigned int nr_eligible_ptes, nr_ptes, max_ptes_none;
 	enum scan_result last_result = SCAN_FAIL;
 	int collapsed = 0;
 	bool alloc_failed = false;
@@ -1540,27 +1490,26 @@ static enum scan_result mthp_collapse(struct mm_struct *mm,
 	while (offset < HPAGE_PMD_NR) {
 		nr_ptes = 1UL << order;
 
-		if (!test_bit(order, &enabled_orders))
+		if (!test_bit(order, &cc->scan_orders))
 			goto next_order;
 
 		max_ptes_none = collapse_max_ptes_none(cc, NULL, order);
-		nr_occupied_ptes = bitmap_weight_from(cc->mthp_present_ptes, offset,
+		nr_eligible_ptes = bitmap_weight_from(cc->eligible_ptes, offset,
 						      offset + nr_ptes);
 
 		/*
-		 * Swap PTEs accepted during the scan are counted in @unmapped,
-		 * not in the present-PTE bitmap. Account them for the PMD-order
-		 * candidate.
+		 * Swap PTEs accepted during the scan are counted in
+		 * cc->scan_unmapped, not in cc->eligible_ptes. Account them for
+		 * the PMD-order candidate.
 		 */
 		if (is_pmd_order(order))
-			nr_occupied_ptes += unmapped;
+			nr_eligible_ptes += cc->scan_unmapped;
 
-		if (nr_occupied_ptes >= nr_ptes - max_ptes_none) {
+		if (nr_eligible_ptes >= nr_ptes - max_ptes_none) {
 			enum scan_result ret;
 
 			collapse_address = address + offset * PAGE_SIZE;
-			ret = collapse_huge_page(mm, collapse_address, referenced,
-						 unmapped, cc, order);
+			ret = collapse_huge_page(mm, collapse_address, cc, order);
 
 			switch (ret) {
 			/* Cases where we continue to next collapse candidate */
@@ -1601,8 +1550,8 @@ static enum scan_result mthp_collapse(struct mm_struct *mm,
 		 * any smaller order enabled. When at the smallest order
 		 * we must always move to the next offset.
 		 */
-		if (order > KHUGEPAGED_MIN_MTHP_ORDER &&
-			(enabled_orders & GENMASK(order - 1, 0))) {
+		if (order > COLLAPSE_MIN_MTHP_ORDER &&
+		    (cc->scan_orders & GENMASK(order - 1, 0))) {
 			order--;
 			continue;
 		}
@@ -1627,14 +1576,14 @@ static enum scan_result mthp_collapse(struct mm_struct *mm,
 	return last_result;
 }
 
-static enum scan_result collapse_scan_pmd(struct mm_struct *mm,
-		struct vm_area_struct *vma, unsigned long start_addr,
-		bool *lock_dropped, struct collapse_control *cc)
+static enum scan_result collapse_scan_anon(struct vm_area_struct *vma,
+		unsigned long start_addr, struct collapse_control *cc)
 {
 	const unsigned int max_ptes_shared = collapse_max_ptes_shared(cc, HPAGE_PMD_ORDER);
 	const unsigned int max_ptes_swap = collapse_max_ptes_swap(cc, HPAGE_PMD_ORDER);
 	unsigned int max_ptes_none = collapse_max_ptes_none(cc, vma, HPAGE_PMD_ORDER);
-	enum tva_type tva_flags = cc->is_khugepaged ? TVA_KHUGEPAGED : TVA_FORCED_COLLAPSE;
+	enum tva_type tva_flags = cc->policy.tva_type;
+	struct mm_struct *mm = vma->vm_mm;
 	pmd_t *pmd;
 	pte_t *pte, *_pte, pteval;
 	int i;
@@ -1656,17 +1605,17 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,
 		goto out;
 	}
 
-	collapse_control_init_scan(cc);
+	collapse_scan_reset(cc);
 
 	enabled_orders = collapse_possible_orders(vma, vma->vm_flags, tva_flags);
 
 	/*
 	 * If PMD is the only enabled order, enforce max_ptes_none, otherwise
 	 * scan all pages to populate the bitmap for mTHP collapse. The bitmap
-	 * is then checked again in mthp_collapse() for each attempted order.
+	 * is then checked again in collapse_anon() for each attempted order.
 	 */
 	if (enabled_orders != BIT(HPAGE_PMD_ORDER))
-		max_ptes_none = KHUGEPAGED_MAX_PTES_LIMIT;
+		max_ptes_none = COLLAPSE_MAX_PTES_LIMIT;
 
 	pte = pte_offset_map_lock(mm, pmd, start_addr, &ptl);
 	if (!pte) {
@@ -1734,7 +1683,7 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,
 		 * If the vma has the VM_DROPPABLE flag, the collapse will
 		 * preserve the lazyfree property without needing to skip.
 		 */
-		if (cc->is_khugepaged && !(vma->vm_flags & VM_DROPPABLE) &&
+		if (cc->policy.anon_skip_lazyfree && !(vma->vm_flags & VM_DROPPABLE) &&
 		    folio_test_lazyfree(folio) && !pte_dirty(pteval)) {
 			result = SCAN_PAGE_LAZYFREE;
 			failed_pfn = folio_pfn(folio);
@@ -1761,8 +1710,8 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,
 			}
 		}
 
-		/* Set bit for occupied pages */
-		__set_bit(i, cc->mthp_present_ptes);
+		/* The scan accepted this PTE as a collapse source */
+		__set_bit(i, cc->eligible_ptes);
 		/*
 		 * Record which node the original page is from and save this
 		 * information to cc->node_load[].
@@ -1800,13 +1749,13 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,
 			goto out_unmap;
 		}
 
-		if (cc->is_khugepaged &&
+		if (cc->policy.anon_require_referenced &&
 		    folio_pte_referenced(folio, vma, addr, pteval))
 			referenced++;
 	}
-	if (cc->is_khugepaged &&
-		   (!referenced ||
-		    (unmapped && referenced < HPAGE_PMD_NR / 2))) {
+	if (cc->policy.anon_require_referenced &&
+	    (!referenced ||
+	     (unmapped && referenced < HPAGE_PMD_NR / 2))) {
 		result = SCAN_LACK_REFERENCED_PAGE;
 	} else {
 		result = SCAN_SUCCEED;
@@ -1814,12 +1763,9 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,
 out_unmap:
 	pte_unmap_unlock(pte, ptl);
 	if (result == SCAN_SUCCEED) {
-		/* collapse_huge_page() expects the lock to be dropped before calling */
-		mmap_read_unlock(mm);
-		result = mthp_collapse(mm, start_addr, referenced,
-				       unmapped, cc, enabled_orders);
-		/* mmap_lock was released above, set lock_dropped */
-		*lock_dropped = true;
+		cc->scan_orders = enabled_orders;
+		cc->scan_referenced = referenced;
+		cc->scan_unmapped = unmapped;
 	}
 out:
 	trace_mm_khugepaged_scan_pmd(mm, failed_pfn, referenced,
@@ -2665,11 +2611,11 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
 	xas_unlock_irq(&xas);
 
 	/*
-	 * Remove pte page tables, so we can re-fault the page as huge.
-	 * If MADV_COLLAPSE, adjust result to call try_collapse_pte_mapped_thp().
+	 * Remove pte page tables, so we can re-fault the page as huge.  A
+	 * caller that wants the PMD mapped now is told to go and do that.
 	 */
 	retract_page_tables(mapping, start);
-	if (cc && !cc->is_khugepaged)
+	if (cc->policy.file_install_pmd)
 		result = SCAN_PTE_MAPPED_HUGEPAGE;
 	folio_unlock(new_folio);
 
@@ -2734,7 +2680,7 @@ static enum scan_result collapse_scan_file(struct mm_struct *mm,
 
 	present = 0;
 	swap = 0;
-	collapse_control_init_scan(cc);
+	collapse_scan_reset(cc);
 	rcu_read_lock();
 	xas_for_each(&xas, folio, start + HPAGE_PMD_NR - 1) {
 		if (xas_retry(&xas, folio))
@@ -2816,53 +2762,78 @@ static enum scan_result collapse_scan_file(struct mm_struct *mm,
 	else
 		cc->progress += HPAGE_PMD_NR;
 
-	if (result == SCAN_SUCCEED) {
-		if (present < HPAGE_PMD_NR - max_ptes_none) {
-			result = SCAN_EXCEED_NONE_PTE;
-			count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
-		} else {
-			result = collapse_file(mm, addr, file, start, cc);
-		}
+	if (result == SCAN_SUCCEED && present < HPAGE_PMD_NR - max_ptes_none) {
+		result = SCAN_EXCEED_NONE_PTE;
+		count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
 	}
 
-	trace_mm_khugepaged_scan_file(mm, failed_pfn, file, present, swap, result);
+	trace_mm_khugepaged_scan_file(mm, failed_pfn, file, present, swap,
+				      result);
 	return result;
 }
 
-/*
- * Try to collapse a single PMD starting at a PMD aligned addr, and return
- * the results.
- */
-static enum scan_result collapse_single_pmd(unsigned long addr,
-		struct vm_area_struct *vma, bool *lock_dropped,
-		struct collapse_control *cc)
+static void collapse_control_init(struct collapse_control *cc)
+{
+	cc->progress = 0;
+	cc->scan_file = NULL;
+}
+
+static enum scan_result collapse_scan_pmd(struct vm_area_struct *vma,
+		unsigned long addr, struct collapse_control *cc)
 {
-	struct mm_struct *mm = vma->vm_mm;
-	bool triggered_wb = false;
 	enum scan_result result;
-	struct file *file;
 	pgoff_t pgoff;
 
-	mmap_assert_locked(mm);
-
-	if (vma_is_anonymous(vma)) {
-		result = collapse_scan_pmd(mm, vma, addr, lock_dropped, cc);
-		goto end;
+	mmap_assert_locked(vma->vm_mm);
+	/* A scan that found work has to have been followed by collapse_pmd() */
+	if (WARN_ON_ONCE(cc->scan_file)) {
+		fput(cc->scan_file);
+		cc->scan_file = NULL;
 	}
 
-	file = get_file(vma->vm_file);
-	pgoff = linear_page_index(vma, addr);
+	if (vma_is_anonymous(vma))
+		return collapse_scan_anon(vma, addr, cc);
 
-	mmap_read_unlock(mm);
-	*lock_dropped = true;
-retry:
-	result = collapse_scan_file(mm, addr, file, pgoff, cc);
+	pgoff = linear_page_index(vma, addr);
+	result = collapse_scan_file(vma->vm_mm, addr, vma->vm_file, pgoff, cc);
+	/*
+	 * SCAN_PTE_MAPPED_HUGEPAGE is work too: the page cache already holds
+	 * the PMD folio, and collapse_pmd() still has to retract the PTE table.
+	 */
+	if (result != SCAN_SUCCEED && result != SCAN_PTE_MAPPED_HUGEPAGE)
+		return result;
 
 	/*
-	 * For MADV_COLLAPSE, when encountering dirty pages, try to writeback,
-	 * then retry the collapse one time.
+	 * A file collapse works on the page cache and never sees a VMA, so take
+	 * what it needs from this one while it is still here.
 	 */
-	if (!cc->is_khugepaged && result == SCAN_PAGE_DIRTY_OR_WRITEBACK &&
+	cc->scan_file = get_file(vma->vm_file);
+	cc->scan_pgoff = pgoff;
+	return result;
+}
+
+static enum scan_result collapse_pmd(struct mm_struct *mm,
+		unsigned long addr, enum scan_result result,
+		struct collapse_control *cc)
+{
+	struct file *file = cc->scan_file;
+	bool triggered_wb = false;
+	pgoff_t pgoff;
+
+	if (!file)
+		return collapse_anon(mm, addr, cc);
+
+	cc->scan_file = NULL;
+	pgoff = cc->scan_pgoff;
+
+	/* The scan found the PMD folio in place: nothing to collapse */
+	if (result == SCAN_PTE_MAPPED_HUGEPAGE)
+		goto put;
+retry:
+	result = collapse_file(mm, addr, file, pgoff, cc);
+
+	/* Dirty pages are worth a writeback and one more try, if asked for */
+	if (cc->policy.file_writeback_dirty && result == SCAN_PAGE_DIRTY_OR_WRITEBACK &&
 	    !triggered_wb && mapping_can_writeback(file->f_mapping)) {
 		const loff_t lstart = (loff_t)pgoff << PAGE_SHIFT;
 		const loff_t lend = lstart + HPAGE_PMD_SIZE - 1;
@@ -2871,25 +2842,49 @@ static enum scan_result collapse_single_pmd(unsigned long addr,
 		triggered_wb = true;
 		goto retry;
 	}
+put:
 	fput(file);
 
+	/*
+	 * A PMD folio is in the page cache, whether the collapse just put it
+	 * there or found it: retract the PTE table, and map the PMD if asked.
+	 */
 	if (result == SCAN_PTE_MAPPED_HUGEPAGE) {
 		mmap_read_lock(mm);
 		if (collapse_test_exit_or_disable(mm))
 			result = SCAN_ANY_PROCESS;
 		else
 			result = try_collapse_pte_mapped_thp(mm, addr,
-							     !cc->is_khugepaged);
+							cc->policy.file_install_pmd);
 		if (result == SCAN_PMD_MAPPED)
 			result = SCAN_SUCCEED;
 		mmap_read_unlock(mm);
 	}
-end:
-	if (cc->is_khugepaged && result == SCAN_SUCCEED)
-		++khugepaged_pages_collapsed;
 	return result;
 }
 
+/*
+ * Try to collapse a single PMD starting at a PMD aligned addr, and return
+ * the results.
+ */
+static enum scan_result collapse_single_pmd(unsigned long addr,
+		struct vm_area_struct *vma, bool *lock_dropped,
+		struct collapse_control *cc)
+{
+	struct mm_struct *mm = vma->vm_mm;
+	enum scan_result result;
+
+	result = collapse_scan_pmd(vma, addr, cc);
+	if (result != SCAN_SUCCEED && result != SCAN_PTE_MAPPED_HUGEPAGE)
+		return result;
+
+	/* The collapse takes its own locks, so give this up */
+	mmap_read_unlock(mm);
+	*lock_dropped = true;
+
+	return collapse_pmd(mm, addr, result, cc);
+}
+
 static void collapse_scan_mm_slot(unsigned int progress_max,
 		enum scan_result *result, struct collapse_control *cc)
 	__releases(&khugepaged_mm_lock)
@@ -2936,7 +2931,8 @@ static void collapse_scan_mm_slot(unsigned int progress_max,
 			cc->progress++;
 			break;
 		}
-		if (!collapse_possible(vma, vma->vm_flags, TVA_KHUGEPAGED)) {
+		if (!collapse_possible_orders(vma, vma->vm_flags,
+					      TVA_KHUGEPAGED)) {
 			cc->progress++;
 			continue;
 		}
@@ -2963,6 +2959,8 @@ static void collapse_scan_mm_slot(unsigned int progress_max,
 
 			*result = collapse_single_pmd(khugepaged_scan.address,
 						      vma, &lock_dropped, cc);
+			if (*result == SCAN_SUCCEED)
+				khugepaged_pages_collapsed++;
 			/* move to next address */
 			khugepaged_scan.address += HPAGE_PMD_SIZE;
 			if (lock_dropped)
@@ -3029,7 +3027,9 @@ static void khugepaged_do_scan(struct collapse_control *cc)
 
 	lru_add_drain_all();
 
-	cc->progress = 0;
+	collapse_control_init(cc);
+	collapse_policy_khugepaged(&cc->policy);
+
 	while (true) {
 		cond_resched();
 
@@ -3244,7 +3244,7 @@ int madvise_collapse(struct vm_area_struct *vma, unsigned long start,
 	BUG_ON(vma->vm_start > start);
 	BUG_ON(vma->vm_end < end);
 
-	if (!collapse_possible(vma, vma->vm_flags, TVA_FORCED_COLLAPSE))
+	if (!collapse_possible_orders(vma, vma->vm_flags, TVA_FORCED_COLLAPSE))
 		return -EINVAL;
 
 	hstart = ALIGN(start, HPAGE_PMD_SIZE);
@@ -3256,10 +3256,9 @@ int madvise_collapse(struct vm_area_struct *vma, unsigned long start,
 	cc = kmalloc_obj(*cc);
 	if (!cc)
 		return -ENOMEM;
-	cc->is_khugepaged = false;
-	cc->progress = 0;
+	collapse_control_init(cc);
+	collapse_policy_madvise(&cc->policy);
 
-	mmgrab(mm);
 	lru_add_drain_all();
 
 	for (addr = hstart; addr < hend; addr += HPAGE_PMD_SIZE) {
@@ -3315,7 +3314,6 @@ int madvise_collapse(struct vm_area_struct *vma, unsigned long start,
 	}
 out_nolock:
 	mmap_assert_locked(mm);
-	mmdrop(mm);
 	kfree(cc);
 
 	return thps == ((hend - hstart) >> HPAGE_PMD_SHIFT) ? 0

21/3 2026/10/14 23:15 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 14834
							output: 18
							thoughts: 391
						

Thoughts:
**Analyzing the Patch Series for KMSAN Fuzzing Needs**

Okay, so I need to figure out if this patch series warrants a dedicated KMSAN fuzzing session. Let's dig in. I'm going to carefully read the diff and dissect the code changes. It looks like it’s touching `mm/khugepaged.c` and introducing `mm/collapse.h`. Alright, let's see what we've got.

In `mm/collapse.h`, we have new definitions for things like `COLLAPSE_MAX_PTES_LIMIT`, `COLLAPSE_MIN_MTHP_ORDER`, an `enum scan_result`, `struct collapse_limits`, `struct collapse_policy`, and `struct collapse_control`. Interesting...

Now, looking at `mm/khugepaged.c`, the diff appears to be refactoring `collapse_control` and `is_khugepaged` into this new `struct collapse_policy`. Wait a minute, what's going on with `madvise_collapse`? Let's take a closer look at the code there:

```c
	cc = kmalloc_obj(*cc);
	if (!cc)
		return -ENOMEM;
-	cc->is_khugepaged = false;
-	cc->progress = 0;
+	collapse_control_init(cc);
+	collapse_policy_madvise(&cc->policy);
```

Okay, now hold on... I need to see exactly how `cc` is being allocated in `madvise_collapse`. Specifically, how does `kmalloc_obj(*cc)` work in comparison to, say, `kzalloc`? Is there a subtle difference in initialization that could lead to issues? Hmm, this warrants a closer look. What's this `kmalloc_obj`? I need to understand its definition and how `collapse_control` is initialized. Let's get `grepper` and see where this function is defined, or maybe I should go back and read the `madvise_collapse` function more carefully. I need to understand how the allocation is happening to see if this change introduces a potential memory safety issue that KMSAN might catch.



22/3 2026/10/14 23:15 tool grepper
0m Args:
{
  "Expression": "kmalloc_obj"
}

Results:
{
  "Output": "\nFull output is too long, showing 200 out of 15849 lines.\nUse more precise expression or PathPrefixes if possible.\n\nNumber of matching lines per file (1688 files in total):\nDocumentation/RCU/Design/Requirements/Requirements.rst:3\nDocumentation/RCU/listRCU.rst:1\nDocumentation/RCU/rcu_dereference.rst:2\nDocumentation/RCU/whatisRCU.rst:2\nDocumentation/core-api/kref.rst:2\nDocumentation/core-api/memory-allocation.rst:2\nDocumentation/kernel-hacking/locking.rst:2\nDocumentation/locking/locktypes.rst:2\nDocumentation/process/coding-style.rst:3\nDocumentation/process/deprecated.rst:4\nDocumentation/sound/kernel-api/writing-an-alsa-driver.rst:2\nDocumentation/spi/spi-summary.rst:1\nDocumentation/translations/it_IT/kernel-hacking/locking.rst:2\nDocumentation/translations/it_IT/locking/locktypes.rst:2\nDocumentation/translations/it_IT/process/coding-style.rst:3\nDocumentation/translations/it_IT/process/deprecated.rst:4\nDocumentation/translations/pt_BR/process/deprecated.rst:4\nDocumentation/translations/sp_SP/process/coding-style.rst:1\nDocumentation/translations/zh_CN/core-api/kref.rst:2\nDocumentation/translations/zh_CN/process/coding-style.rst:1\nDocumentation/translations/zh_TW/process/coding-style.rst:1\narch/alpha/kernel/core_marvel.c:2\narch/alpha/kernel/core_titan.c:2\narch/alpha/kernel/module.c:1\narch/alpha/kernel/pci.c:1\narch/arc/kernel/unwind.c:1\narch/arm/common/locomo.c:1\narch/arm/common/sa1111.c:1\narch/arm/kernel/unwind.c:1\narch/arm/mach-omap2/omap-iommu.c:1\narch/arm/mach-omap2/pm34xx.c:1\narch/arm/mach-omap2/pm44xx.c:1\narch/arm/mm/pgd.c:1\narch/arm/probes/kprobes/test-core.c:1\narch/arm64/crypto/aes-neonbs-glue.c:2\narch/arm64/kvm/pmu-emul.c:1\narch/arm64/kvm/vgic/vgic-debug.c:2\narch/arm64/kvm/vgic/vgic-init.c:1\narch/m68k/emu/nfblock.c:1\narch/m68k/mm/kmap.c:1\narch/mips/alchemy/common/dbdma.c:2\narch/mips/kernel/module.c:1\narch/mips/kernel/vpe.c:1\narch/parisc/kernel/inventory.c:2\narch/parisc/kernel/processor.c:1\narch/parisc/kernel/unwind.c:2\narch/powerpc/kernel/nvram_64.c:1\narch/powerpc/kvm/e500_mmu.c:2\narch/powerpc/lib/rheap.c:2\narch/powerpc/mm/book3s64/mmu_context.c:2\n... and 1638 more files\n\nDocumentation/RCU/Design/Requirements/Requirements.rst=203=non-\\ ``NULL``, locklessly accessing the ``-\u003ea`` and ``-\u003eb`` fields.\n--\nDocumentation/RCU/Design/Requirements/Requirements.rst-208-       2 {\nDocumentation/RCU/Design/Requirements/Requirements.rst:209:       3   p = kmalloc_obj(*p);\nDocumentation/RCU/Design/Requirements/Requirements.rst-210-       4   if (!p)\n--\nDocumentation/RCU/Design/Requirements/Requirements.rst=225=their rights to reorder this code as follows:\n--\nDocumentation/RCU/Design/Requirements/Requirements.rst-230-       2 {\nDocumentation/RCU/Design/Requirements/Requirements.rst:231:       3   p = kmalloc_obj(*p);\nDocumentation/RCU/Design/Requirements/Requirements.rst-232-       4   if (!p)\n--\nDocumentation/RCU/Design/Requirements/Requirements.rst=261=shows an example of insertion:\n--\nDocumentation/RCU/Design/Requirements/Requirements.rst-266-       2 {\nDocumentation/RCU/Design/Requirements/Requirements.rst:267:       3   p = kmalloc_obj(*p);\nDocumentation/RCU/Design/Requirements/Requirements.rst-268-       4   if (!p)\n--\nDocumentation/RCU/listRCU.rst=267=The RCU version of audit_upd_rule() is as follows::\n--\nDocumentation/RCU/listRCU.rst-278-\t\t\tif (!audit_compare_rule(rule, \u0026e-\u003erule)) {\nDocumentation/RCU/listRCU.rst:279:\t\t\t\tne = kmalloc_obj(*entry, GFP_ATOMIC);\nDocumentation/RCU/listRCU.rst-280-\t\t\t\tif (ne == NULL)\n--\nDocumentation/RCU/rcu_dereference.rst=225=precautions.  To see this, consider the following code fragment::\n--\nDocumentation/RCU/rcu_dereference.rst-238-\nDocumentation/RCU/rcu_dereference.rst:239:\t\tp = kmalloc_obj(*p);\nDocumentation/RCU/rcu_dereference.rst-240-\t\tif (p == NULL)\n--\nDocumentation/RCU/rcu_dereference.rst=281=Then one approach is to use locking, for example, as follows::\n--\nDocumentation/RCU/rcu_dereference.rst-295-\nDocumentation/RCU/rcu_dereference.rst:296:\t\tp = kmalloc_obj(*p);\nDocumentation/RCU/rcu_dereference.rst-297-\t\tif (p == NULL)\n--\nDocumentation/RCU/whatisRCU.rst=441=uses of RCU may be found in listRCU.rst and NMI-RCU.rst.\n--\nDocumentation/RCU/whatisRCU.rst-470-\nDocumentation/RCU/whatisRCU.rst:471:\t\tnew_fp = kmalloc_obj(*new_fp);\nDocumentation/RCU/whatisRCU.rst-472-\t\tspin_lock(\u0026foo_mutex);\n--\nDocumentation/RCU/whatisRCU.rst=553=The foo_update_a() function might then be written as follows::\n--\nDocumentation/RCU/whatisRCU.rst-572-\nDocumentation/RCU/whatisRCU.rst:573:\t\tnew_fp = kmalloc_obj(*new_fp);\nDocumentation/RCU/whatisRCU.rst-574-\t\tspin_lock(\u0026foo_mutex);\n--\nDocumentation/core-api/kref.rst=39=kref_init as so::\n--\nDocumentation/core-api/kref.rst-42-\nDocumentation/core-api/kref.rst:43:     data = kmalloc_obj(*data);\nDocumentation/core-api/kref.rst-44-     if (!data)\n--\nDocumentation/core-api/kref.rst=81=thread to process::\n--\nDocumentation/core-api/kref.rst-102-\tstruct task_struct *task;\nDocumentation/core-api/kref.rst:103:\tdata = kmalloc_obj(*data);\nDocumentation/core-api/kref.rst-104-\tif (!data)\n--\nDocumentation/core-api/memory-allocation.rst=151=conveniently allocate a single object or arrays of objects with kzalloc_obj()\nDocumentation/core-api/memory-allocation.rst:152:and kmalloc_obj() and their array versions kzalloc_objs() and\nDocumentation/core-api/memory-allocation.rst:153:kmalloc_objs(). These helpers only need the type of the object that should be\nDocumentation/core-api/memory-allocation.rst-154-allocated and the count of elements in the array for the array versions.\n--\nDocumentation/kernel-hacking/locking.rst=383=to protect the cache and all the objects within it. Here's the code::\n--\nDocumentation/kernel-hacking/locking.rst-444-\nDocumentation/kernel-hacking/locking.rst:445:            if ((obj = kmalloc_obj(*obj)) == NULL)\nDocumentation/kernel-hacking/locking.rst-446-                    return -ENOMEM;\n--\nDocumentation/kernel-hacking/locking.rst=499=which are taken away, and the ``+`` are lines which are added.\n--\nDocumentation/kernel-hacking/locking.rst-519-\nDocumentation/kernel-hacking/locking.rst:520:             if ((obj = kmalloc_obj(*obj)) == NULL)\nDocumentation/kernel-hacking/locking.rst-521-                     return -ENOMEM;\n--\nDocumentation/locking/locktypes.rst=498=works perfectly::\n--\nDocumentation/locking/locktypes.rst-500-  raw_spin_lock(\u0026lock);\nDocumentation/locking/locktypes.rst:501:  p = kmalloc_obj(*p, GFP_ATOMIC);\nDocumentation/locking/locktypes.rst-502-\n--\nDocumentation/locking/locktypes.rst=507=preemption on PREEMPT_RT kernels::\n--\nDocumentation/locking/locktypes.rst-509-  spin_lock(\u0026lock);\nDocumentation/locking/locktypes.rst:510:  p = kmalloc_obj(*p, GFP_ATOMIC);\nDocumentation/locking/locktypes.rst-511-\n--\nDocumentation/process/coding-style.rst=938=The kernel provides the following general purpose memory allocators:\nDocumentation/process/coding-style.rst:939:kmalloc(), kzalloc(), kmalloc_objs(), kzalloc_objs(), vmalloc(), and\nDocumentation/process/coding-style.rst-940-vzalloc().  Please refer to the API documentation for further information\n--\nDocumentation/process/coding-style.rst=944=The preferred form for passing a size of a struct is the following:\n--\nDocumentation/process/coding-style.rst-947-\nDocumentation/process/coding-style.rst:948:\tp = kmalloc_obj(*p, ...);\nDocumentation/process/coding-style.rst-949-\n--\nDocumentation/process/coding-style.rst=958=The preferred form for allocating an array is the following:\n--\nDocumentation/process/coding-style.rst-961-\nDocumentation/process/coding-style.rst:962:\tp = kmalloc_objs(*p, n, ...);\nDocumentation/process/coding-style.rst-963-\n--\nDocumentation/process/deprecated.rst=386=may help with alignment, wrap-around, or additional hardening. The\nDocumentation/process/deprecated.rst:387:kmalloc_obj()-family of macros provide this introspection, which can be\nDocumentation/process/deprecated.rst-388-used for the common code patterns for single, array, and flexible object\n--\nDocumentation/process/deprecated.rst=398=become, respectively::\nDocumentation/process/deprecated.rst-399-\nDocumentation/process/deprecated.rst:400:\tptr = kmalloc_obj(*ptr [, gfp] );\nDocumentation/process/deprecated.rst-401-\tptr = kzalloc_obj(*ptr [, gfp] );\nDocumentation/process/deprecated.rst:402:\tptr = kmalloc_objs(*ptr, count [, gfp] );\nDocumentation/process/deprecated.rst-403-\tptr = kzalloc_objs(*ptr, count [, gfp] );\nDocumentation/process/deprecated.rst-404-\tptr = kmalloc_flex(*ptr, flex_member, count [, gfp] );\nDocumentation/process/deprecated.rst:405:\t__auto_type ptr = kmalloc_obj(struct foo [, gfp] );\nDocumentation/process/deprecated.rst-406-\n--\nDocumentation/sound/kernel-api/writing-an-alsa-driver.rst=1734=callback::\n--\nDocumentation/sound/kernel-api/writing-an-alsa-driver.rst-1739-          ....\nDocumentation/sound/kernel-api/writing-an-alsa-driver.rst:1740:          data = kmalloc_obj(*data);\nDocumentation/sound/kernel-api/writing-an-alsa-driver.rst-1741-          substream-\u003eruntime-\u003eprivate_data = data;\n--\nDocumentation/sound/kernel-api/writing-an-alsa-driver.rst=3302=destructor function is set in the ``private_free`` field::\nDocumentation/sound/kernel-api/writing-an-alsa-driver.rst-3303-\nDocumentation/sound/kernel-api/writing-an-alsa-driver.rst:3304:  struct mydata *p = kmalloc_obj(*p);\nDocumentation/sound/kernel-api/writing-an-alsa-driver.rst-3305-  hw-\u003eprivate_data = p;\n--\nDocumentation/spi/spi-summary.rst=242=And SOC-specific utility code might look something like::\n--\nDocumentation/spi/spi-summary.rst-251-\nDocumentation/spi/spi-summary.rst:252:\t\tpdata2 = kmalloc_obj(*pdata2);\nDocumentation/spi/spi-summary.rst-253-\t\t*pdata2 = pdata;\n--\nDocumentation/translations/it_IT/kernel-hacking/locking.rst=403=e tutti gli oggetti che contiene. Ecco il codice::\n--\nDocumentation/translations/it_IT/kernel-hacking/locking.rst-464-\nDocumentation/translations/it_IT/kernel-hacking/locking.rst:465:            if ((obj = kmalloc_obj(*obj)) == NULL)\nDocumentation/translations/it_IT/kernel-hacking/locking.rst-466-                    return -ENOMEM;\n--\nDocumentation/translations/it_IT/kernel-hacking/locking.rst=519=sono quelle rimosse, mentre quelle ``+`` sono quelle aggiunte.\n--\nDocumentation/translations/it_IT/kernel-hacking/locking.rst-539-\nDocumentation/translations/it_IT/kernel-hacking/locking.rst:540:             if ((obj = kmalloc_obj(*obj)) == NULL)\nDocumentation/translations/it_IT/kernel-hacking/locking.rst-541-                     return -ENOMEM;\n--\nDocumentation/translations/it_IT/locking/locktypes.rst=488=memoria. Su un kernel non-PREEMPT_RT il seguente codice funziona perfettamente::\n--\nDocumentation/translations/it_IT/locking/locktypes.rst-490-  raw_spin_lock(\u0026lock);\nDocumentation/translations/it_IT/locking/locktypes.rst:491:  p = kmalloc_obj(*p, GFP_ATOMIC);\nDocumentation/translations/it_IT/locking/locktypes.rst-492-\n--\nDocumentation/translations/it_IT/locking/locktypes.rst=497=PREEMPT_RT::\n--\nDocumentation/translations/it_IT/locking/locktypes.rst-499-  spin_lock(\u0026lock);\nDocumentation/translations/it_IT/locking/locktypes.rst:500:  p = kmalloc_obj(*p, GFP_ATOMIC);\nDocumentation/translations/it_IT/locking/locktypes.rst-501-\n--\nDocumentation/translations/it_IT/process/coding-style.rst=940=Il kernel fornisce i seguenti assegnatori ad uso generico:\nDocumentation/translations/it_IT/process/coding-style.rst:941:kmalloc(), kzalloc(), kmalloc_objs(), kzalloc_objs(), vmalloc(), e vzalloc().\nDocumentation/translations/it_IT/process/coding-style.rst-942-Per maggiori informazioni, consultate la documentazione dell'API:\n--\nDocumentation/translations/it_IT/process/coding-style.rst=945=Il modo preferito per passare la dimensione di una struttura è il seguente:\n--\nDocumentation/translations/it_IT/process/coding-style.rst-948-\nDocumentation/translations/it_IT/process/coding-style.rst:949:\tp = kmalloc_obj(*p, ...);\nDocumentation/translations/it_IT/process/coding-style.rst-950-\n--\nDocumentation/translations/it_IT/process/coding-style.rst=959=Il modo preferito per assegnare un vettore è il seguente:\n--\nDocumentation/translations/it_IT/process/coding-style.rst-962-\nDocumentation/translations/it_IT/process/coding-style.rst:963:\tp = kmalloc_objs(*p, n, ...);\nDocumentation/translations/it_IT/process/coding-style.rst-964-\n--\nDocumentation/translations/it_IT/process/deprecated.rst=428=l'overflow, o per un ulteriore irrobustimento. Le macro della famiglia\nDocumentation/translations/it_IT/process/deprecated.rst:429:kmalloc_obj() forniscono questa introspezione, e possono essere usate\nDocumentation/translations/it_IT/process/deprecated.rst-430-per i più comuni schemi di codice per l'allocazione di un singolo\n--\nDocumentation/translations/it_IT/process/deprecated.rst=441=diventano, rispettivamente::\nDocumentation/translations/it_IT/process/deprecated.rst-442-\nDocumentation/translations/it_IT/process/deprecated.rst:443:\tptr = kmalloc_obj(*ptr [, gfp] );\nDocumentation/translations/it_IT/process/deprecated.rst-444-\tptr = kzalloc_obj(*ptr [, gfp] );\nDocumentation/translations/it_IT/process/deprecated.rst:445:\tptr = kmalloc_objs(*ptr, count [, gfp] );\nDocumentation/translations/it_IT/process/deprecated.rst-446-\tptr = kzalloc_objs(*ptr, count [, gfp] );\nDocumentation/translations/it_IT/process/deprecated.rst-447-\tptr = kmalloc_flex(*ptr, flex_member, count [, gfp] );\nDocumentation/translations/it_IT/process/deprecated.rst:448:\t__auto_type ptr = kmalloc_obj(struct foo [, gfp] );\nDocumentation/translations/it_IT/process/deprecated.rst-449-\n--\nDocumentation/translations/pt_BR/process/deprecated.rst=397=possa ajudar com alinhamento, estouros de capacidade (*wrap-around*) ou\nDocumentation/translations/pt_BR/process/deprecated.rst:398:proteções adicionais (*hardening*). A família de macros kmalloc_obj() fornece\nDocumentation/translations/pt_BR/process/deprecated.rst-399-essa introspecção, que pode ser usada para os padrões de código comuns de\n--\nDocumentation/translations/pt_BR/process/deprecated.rst=410=tornam-se, respectivamente::\nDocumentation/translations/pt_BR/process/deprecated.rst-411-\nDocumentation/translations/pt_BR/process/deprecated.rst:412:        ptr = kmalloc_obj(*ptr [, gfp] );\nDocumentation/translations/pt_BR/process/deprecated.rst-413-        ptr = kzalloc_obj(*ptr [, gfp] );\nDocumentation/translations/pt_BR/process/deprecated.rst:414:        ptr = kmalloc_objs(*ptr, count [, gfp] );\nDocumentation/translations/pt_BR/process/deprecated.rst-415-        ptr = kzalloc_objs(*ptr, count [, gfp] );\n\n"
}

23/3 2026/10/14 23:15 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 20617
							output: 37
							thoughts: 45
						

Thoughts:
Here's my analysis of what I'm thinking, rendered as if I'm the one having these thoughts:

**Investigating the `kmalloc_obj` in Relation to `madvise_collapse`**

Okay, so I need to understand what's happening with `kmalloc_obj` in relation to `madvise_collapse`. The context here is likely memory management, given the function names and the path to `mm/khugepaged.c`. My immediate thought is to trace the evolution or usage of `kmalloc_obj`, and how it interacts within the `madvise_collapse` function. I will check the state of the object, before and within this function, to understand how they are related. My next step will be to dive into the code of `madvise_collapse` itself, located in that `khugepaged.c` file. This should give me the core logic and context needed to piece things together. I'm expecting this will shed light on memory collapsing or similar operations.



24/3 2026/10/14 23:15 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 3240,
  "LineCount": 80
}

Results:
{
  "Contents": "3240:\t\tenum scan_result last_fail = SCAN_FAIL;\n3241:\t\tint thps = 0;\n3242:\t\tbool mmap_unlocked = false;\n3243:\t\n3244:\t\tBUG_ON(vma-\u003evm_start \u003e start);\n3245:\t\tBUG_ON(vma-\u003evm_end \u003c end);\n3246:\t\n3247:\t\tif (!collapse_possible_orders(vma, vma-\u003evm_flags, TVA_FORCED_COLLAPSE))\n3248:\t\t\treturn -EINVAL;\n3249:\t\n3250:\t\thstart = ALIGN(start, HPAGE_PMD_SIZE);\n3251:\t\thend = ALIGN_DOWN(end, HPAGE_PMD_SIZE);\n3252:\t\n3253:\t\tif (hstart \u003e= hend)\n3254:\t\t\treturn 0;\n3255:\t\n3256:\t\tcc = kmalloc_obj(*cc);\n3257:\t\tif (!cc)\n3258:\t\t\treturn -ENOMEM;\n3259:\t\tcollapse_control_init(cc);\n3260:\t\tcollapse_policy_madvise(\u0026cc-\u003epolicy);\n3261:\t\n3262:\t\tlru_add_drain_all();\n3263:\t\n3264:\t\tfor (addr = hstart; addr \u003c hend; addr += HPAGE_PMD_SIZE) {\n3265:\t\t\tenum scan_result result = SCAN_FAIL;\n3266:\t\n3267:\t\t\tif (mmap_unlocked) {\n3268:\t\t\t\tcond_resched();\n3269:\t\t\t\tmmap_read_lock(mm);\n3270:\t\t\t\tmmap_unlocked = false;\n3271:\t\t\t\t*lock_dropped = true;\n3272:\t\t\t\tresult = hugepage_vma_revalidate(mm, addr, false, \u0026vma,\n3273:\t\t\t\t\t\t\t\t cc, HPAGE_PMD_ORDER);\n3274:\t\t\t\tif (result != SCAN_SUCCEED) {\n3275:\t\t\t\t\tlast_fail = result;\n3276:\t\t\t\t\tgoto out_nolock;\n3277:\t\t\t\t}\n3278:\t\n3279:\t\t\t\thend = min(hend, vma-\u003evm_end \u0026 HPAGE_PMD_MASK);\n3280:\t\t\t}\n3281:\t\n3282:\t\t\tresult = collapse_single_pmd(addr, vma, \u0026mmap_unlocked, cc);\n3283:\t\n3284:\t\t\tswitch (result) {\n3285:\t\t\tcase SCAN_SUCCEED:\n3286:\t\t\tcase SCAN_PMD_MAPPED:\n3287:\t\t\t\t++thps;\n3288:\t\t\t\tbreak;\n3289:\t\t\t/* Whitelisted set of results where continuing OK */\n3290:\t\t\tcase SCAN_NO_PTE_TABLE:\n3291:\t\t\tcase SCAN_PTE_NON_PRESENT:\n3292:\t\t\tcase SCAN_PTE_UFFD:\n3293:\t\t\tcase SCAN_LACK_REFERENCED_PAGE:\n3294:\t\t\tcase SCAN_PAGE_NULL:\n3295:\t\t\tcase SCAN_PAGE_COUNT:\n3296:\t\t\tcase SCAN_PAGE_LOCK:\n3297:\t\t\tcase SCAN_PAGE_COMPOUND:\n3298:\t\t\tcase SCAN_PAGE_LRU:\n3299:\t\t\tcase SCAN_DEL_PAGE_LRU:\n3300:\t\t\t\tlast_fail = result;\n3301:\t\t\t\tbreak;\n3302:\t\t\tdefault:\n3303:\t\t\t\tlast_fail = result;\n3304:\t\t\t\t/* Other error, exit */\n3305:\t\t\t\tgoto out_maybelock;\n3306:\t\t\t}\n3307:\t\t}\n3308:\t\n3309:\tout_maybelock:\n3310:\t\t/* Caller expects us to hold mmap_lock on return */\n3311:\t\tif (mmap_unlocked) {\n3312:\t\t\t*lock_dropped = true;\n3313:\t\t\tmmap_read_lock(mm);\n3314:\t\t}\n3315:\tout_nolock:\n3316:\t\tmmap_assert_locked(mm);\n3317:\t\tkfree(cc);\n3318:\t\n3319:\t\treturn thps == ((hend - hstart) \u003e\u003e HPAGE_PMD_SHIFT) ? 0\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 22081
							output: 37
							thoughts: 3913
						

Thoughts:
**Analysis of Collapse Control Initialization and Usage in madvise_collapse**

Okay, let's break this down. My initial thought was: "Hang on, `cc = kmalloc_obj(*cc);`... was that always there?" The Git diff confirmed that this `kmalloc_obj` was *not* part of the patch. Now, the `collapse_control` struct itself: I need to understand what's in there. I see it contains a `collapse_policy`, node load data, a progress counter, an allocation nodemask, bitmaps for PTEs, and some anonymous and file-specific scan data. The key is how this struct is *used*.

The memory allocation: `kmalloc_obj(*cc)`. Crucially, `kmalloc_obj` is not zeroing the memory. That’s a key piece of information! It's calling `kmalloc(sizeof(*cc), ...)` which *might* leave junk data around. I need to see what's *initialized* later.

I quickly check `collapse_control_init` and `collapse_policy_madvise`.  `collapse_control_init` sets `progress` to zero and `scan_file` to `NULL`. `collapse_policy_madvise` sets up the collapse policy, which includes things like the maximum number of PTEs, whether to skip lazy free pages, require referenced pages, and what GFP flags to use.

Okay, now let's follow the data flow of `cc`. In `madvise_collapse`, I see `cc` being passed to `collapse_single_pmd`. In `collapse_single_pmd`, `collapse_scan_pmd` is called. Critically, within `collapse_scan_pmd`, there are separate paths for anonymous and file VMAs. The anon path calls `collapse_scan_anon`, and file VMs call `collapse_scan_file`.

In *both* the file and anonymous paths, `collapse_scan_reset(cc)` is called, which initializes the `node_load`, `alloc_nmask`, and `eligible_ptes`. So at the *start* of *every* `madvise_collapse` iteration, some important fields of `cc` *are* being cleared to a known state.

Now, if a scan is a *file scan* and returns `SCAN_SUCCEED` (or `SCAN_PTE_MAPPED_HUGEPAGE`), the code path becomes more interesting: `cc->scan_file` is set to point to the file, and `cc->scan_pgoff` is set. Then in `collapse_pmd`, there's a check: if `cc->scan_file` is *not* `NULL`, which is the case when file collapse is in process, then a file-specific collapse happens. That collapse *sets `cc->scan_file = NULL`* and `fput`s the file.

The `WARN_ON_ONCE` within `collapse_scan_pmd` is important. This means the code expects `cc->scan_file` to be `NULL` at the start of a scan. However if `cc->scan_file` is *not* `NULL`, then there's an `fput` of the file and `cc->scan_file = NULL` is set. This makes sure that `cc->scan_file` is reset for the next iteration.

What if the VMA *is* anonymous?  If `collapse_scan_anon` succeeds (doesn't return `SCAN_VMA_CHECK`), it stores data in `cc` and calls `collapse_pmd`. Since `cc->scan_file` is still `NULL`, the anonymous code path inside `collapse_pmd` will run. The data set in `collapse_scan_anon` (scan_orders, scan_referenced, scan_unmapped, and eligible_ptes) is *used* in `collapse_anon`, the file collapse path will not be used in this situation, and there is no call to `get_file`!

So, in the next loop iteration, if the VMA *is* anonymous,  `cc->scan_file` will be `NULL`. `collapse_scan_reset(cc)` will run at the start of `collapse_scan_anon`, initializing the appropriate fields.  However, the `cc->scan_file` variable is set to null, so it shouldn't cause problems in later iterations.

Regarding `khugepaged_collapse_control`: It's a static struct, which means it will be initialized to zero (BSS section). `khugepaged_do_scan` calls `collapse_control_init` and `collapse_policy_khugepaged`, ensuring


26/3 2026/10/14 23:16 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 1030,
  "LineCount": 40
}

Results:
{
  "Contents": "1030:\t\n1031:\t\t/*\n1032:\t\t * We cannot collapse VMA regions that do not span the full PMD. This is\n1033:\t\t * due to the potential of the PMD being shared by another VMA leaving\n1034:\t\t * us vulnerable to a race condition. Always check the PMD order here to\n1035:\t\t * ensure its not shared by another VMA. We'd need to lock all VMAs in\n1036:\t\t * the PMD range to support this.\n1037:\t\t */\n1038:\t\tif (!thp_vma_suitable_order(vma, address, PMD_ORDER))\n1039:\t\t\treturn SCAN_ADDRESS_RANGE;\n1040:\t\tif (!thp_vma_allowable_orders(vma, vma-\u003evm_flags, type, BIT(order)))\n1041:\t\t\treturn SCAN_VMA_CHECK;\n1042:\t\t/*\n1043:\t\t * Anon VMA expected, the address may be unmapped then\n1044:\t\t * remapped to file after khugepaged reacquired the mmap_lock.\n1045:\t\t *\n1046:\t\t * thp_vma_allowable_orders() may return true for qualified file\n1047:\t\t * vmas.\n1048:\t\t */\n1049:\t\tif (expect_anon \u0026\u0026 (!vma_has_anon_rmap(vma) || !vma_is_anonymous(vma)))\n1050:\t\t\treturn SCAN_PAGE_ANON;\n1051:\t\treturn SCAN_SUCCEED;\n1052:\t}\n1053:\t\n1054:\tstatic inline enum scan_result check_pmd_state(pmd_t *pmd)\n1055:\t{\n1056:\t\tpmd_t pmde = pmdp_get_lockless(pmd);\n1057:\t\n1058:\t\tif (pmd_none(pmde))\n1059:\t\t\treturn SCAN_NO_PTE_TABLE;\n1060:\t\n1061:\t\t/*\n1062:\t\t * The folio may be under migration when khugepaged is trying to\n1063:\t\t * collapse it. Migration success or failure will eventually end\n1064:\t\t * up with a present PMD mapping a folio again.\n1065:\t\t */\n1066:\t\tif (pmd_is_migration_entry(pmde))\n1067:\t\t\treturn SCAN_PMD_MAPPED;\n1068:\t\tif (!pmd_present(pmde))\n1069:\t\t\treturn SCAN_NO_PTE_TABLE;\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 27742
							output: 30
							thoughts: 24
						

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

**Tracing Down `collapse_find_target_node`**

Alright, let's get down to brass tacks. I need to understand the implementation of `collapse_find_target_node`. Given the context, I'm going to start with the obvious and reach for `grep`. I'll need to locate where this function is defined, and the source code is likely the most immediate place to find the answer.



28/3 2026/10/14 23:16 tool grepper
0m Args:
{
  "Expression": "collapse_find_target_node",
  "PathPrefixes": [
    "mm/"
  ]
}

Results:
{
  "Output": "mm/khugepaged.c=969=static void collapse_policy_madvise(struct collapse_policy *p)\n--\nmm/khugepaged.c-985-#ifdef CONFIG_NUMA\nmm/khugepaged.c:986:static int collapse_find_target_node(struct collapse_control *cc)\nmm/khugepaged.c-987-{\n--\nmm/khugepaged.c-1004-#else\nmm/khugepaged.c:1005:static int collapse_find_target_node(struct collapse_control *cc)\nmm/khugepaged.c-1006-{\n--\nmm/khugepaged.c=1202=static enum scan_result alloc_charge_folio(struct folio **foliop, struct mm_struct *mm,\n--\nmm/khugepaged.c-1205-\tgfp_t gfp = cc-\u003epolicy.gfp;\nmm/khugepaged.c:1206:\tint node = collapse_find_target_node(cc);\nmm/khugepaged.c-1207-\tstruct folio *folio;\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 28200
							output: 36
							thoughts: 34
						

Thoughts:
Okay, let's dive into this. I'm going to take a look at the `collapse_find_target_node` function, specifically lines 985-1015 within the `mm/khugepaged.c` file. I need to understand its logic and how it relates to the larger context of the kernel's huge page management. Let's see... I'm expecting this function to be crucial in determining which node is the most suitable target for page collapsing operations. I'm looking for the criteria it uses for selection – is it based on free memory, NUMA node proximity, or perhaps some other balancing factor? I'll pay close attention to the data structures it interacts with, likely the node structure and potentially some zone-related data, as it's probably trying to find the best place to allocate the new huge page. I'll need to confirm that this doesn't introduce any race conditions and that the chosen target is suitable from memory pressure perspectives and that it considers the NUMA layout. I'm also anticipating that it likely involves some form of heuristics, perhaps a best-effort approach to optimize page collapsing. I'm keen to understand the trade-offs it's making in its decision-making process.



30/3 2026/10/14 23:16 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 985,
  "LineCount": 30
}

Results:
{
  "Contents": " 985:\t#ifdef CONFIG_NUMA\n 986:\tstatic int collapse_find_target_node(struct collapse_control *cc)\n 987:\t{\n 988:\t\tint nid, target_node = 0, max_value = 0;\n 989:\t\n 990:\t\t/* find first node with max normal pages hit */\n 991:\t\tfor (nid = 0; nid \u003c MAX_NUMNODES; nid++)\n 992:\t\t\tif (cc-\u003enode_load[nid] \u003e max_value) {\n 993:\t\t\t\tmax_value = cc-\u003enode_load[nid];\n 994:\t\t\t\ttarget_node = nid;\n 995:\t\t\t}\n 996:\t\n 997:\t\tfor_each_online_node(nid) {\n 998:\t\t\tif (max_value == cc-\u003enode_load[nid])\n 999:\t\t\t\tnode_set(nid, cc-\u003ealloc_nmask);\n1000:\t\t}\n1001:\t\n1002:\t\treturn target_node;\n1003:\t}\n1004:\t#else\n1005:\tstatic int collapse_find_target_node(struct collapse_control *cc)\n1006:\t{\n1007:\t\treturn 0;\n1008:\t}\n1009:\t#endif\n1010:\t\n1011:\t/*\n1012:\t * If mmap_lock temporarily dropped, revalidate vma\n1013:\t * after taking the mmap_lock again.\n1014:\t * Returns enum scan_result value.\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 28963
							output: 37
							thoughts: 441
						

Thoughts:
**Analyzing the Refactoring of `collapse_scan_reset`**

Okay, let's break this down. I'm looking at the refactoring of `collapse_scan_reset(cc)`. It's pretty straightforward: it zero-initializes `cc->node_load`, clears `cc->alloc_nmask`, and zeros `cc->eligible_ptes`. That's standard practice when dealing with these data structures.

But wait a minute... before this patch, what function was doing this initialization? Ah, it was `collapse_control_init_scan`! Looking at the before and after code, it was **literally** doing the same thing. They just changed the name! The functionality is identical: both functions are memset'ing node load to zero, clearing the allocation mask, and zeroing the eligible PTE bitmap. That's a classic case of code duplication being cleaned up. It's good to see that kind of refactoring.

Now, a more critical question arises. Before this refactoring, did we have any potential read-before-write issues? Is there a path where either `cc->node_load` or `cc->alloc_nmask` could be read without being initialized? I need to trace the initialization and usage to be sure.

Let's look at the initialization sequence. In `madvise_collapse`, `collapse_control_init(cc)` is called, followed by `collapse_policy_madvise(&cc->policy)`. Then, for each PMD, `collapse_single_pmd` is called, which then leads to `collapse_scan_pmd`. Within `collapse_scan_pmd`, if the VMA is anon, `collapse_scan_anon` is called.

Okay, I've got a hunch. It seems to initialize cc within a single madvise call. I need to make sure that the initialization occurs as planned and isn't dependent on another call that's potentially made outside of madvise. I should verify that both node_load and alloc_nmask are definitely initialized before being accessed. I need to double-check `collapse_scan_anon` itself for any potential issues here. In `mm/khugepaged.c`, specifically lines 1600-1615, I think that's where I need to focus my attention. It is a critical path for anon VMAs and I need to ensure there are no issues. Let's read this function more closely.



32/3 2026/10/14 23:16 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 1575,
  "LineCount": 45
}

Results:
{
  "Contents": "1575:\t\t\treturn SCAN_ALLOC_HUGE_PAGE_FAIL;\n1576:\t\treturn last_result;\n1577:\t}\n1578:\t\n1579:\tstatic enum scan_result collapse_scan_anon(struct vm_area_struct *vma,\n1580:\t\t\tunsigned long start_addr, struct collapse_control *cc)\n1581:\t{\n1582:\t\tconst unsigned int max_ptes_shared = collapse_max_ptes_shared(cc, HPAGE_PMD_ORDER);\n1583:\t\tconst unsigned int max_ptes_swap = collapse_max_ptes_swap(cc, HPAGE_PMD_ORDER);\n1584:\t\tunsigned int max_ptes_none = collapse_max_ptes_none(cc, vma, HPAGE_PMD_ORDER);\n1585:\t\tenum tva_type tva_flags = cc-\u003epolicy.tva_type;\n1586:\t\tstruct mm_struct *mm = vma-\u003evm_mm;\n1587:\t\tpmd_t *pmd;\n1588:\t\tpte_t *pte, *_pte, pteval;\n1589:\t\tint i;\n1590:\t\tint none_or_zero = 0, shared = 0, referenced = 0;\n1591:\t\tenum scan_result result = SCAN_FAIL;\n1592:\t\tstruct page *page = NULL;\n1593:\t\tstruct folio *folio = NULL;\n1594:\t\tunsigned long failed_pfn = -1;\n1595:\t\tunsigned long addr;\n1596:\t\tunsigned long enabled_orders;\n1597:\t\tspinlock_t *ptl;\n1598:\t\tint node = NUMA_NO_NODE, unmapped = 0;\n1599:\t\n1600:\t\tVM_BUG_ON(start_addr \u0026 ~HPAGE_PMD_MASK);\n1601:\t\n1602:\t\tresult = find_pmd_or_thp_or_none(mm, start_addr, \u0026pmd);\n1603:\t\tif (result != SCAN_SUCCEED) {\n1604:\t\t\tcc-\u003eprogress++;\n1605:\t\t\tgoto out;\n1606:\t\t}\n1607:\t\n1608:\t\tcollapse_scan_reset(cc);\n1609:\t\n1610:\t\tenabled_orders = collapse_possible_orders(vma, vma-\u003evm_flags, tva_flags);\n1611:\t\n1612:\t\t/*\n1613:\t\t * If PMD is the only enabled order, enforce max_ptes_none, otherwise\n1614:\t\t * scan all pages to populate the bitmap for mTHP collapse. The bitmap\n1615:\t\t * is then checked again in collapse_anon() for each attempted order.\n1616:\t\t */\n1617:\t\tif (enabled_orders != BIT(HPAGE_PMD_ORDER))\n1618:\t\t\tmax_ptes_none = COLLAPSE_MAX_PTES_LIMIT;\n1619:\t\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 30765
							output: 37
							thoughts: 418
						

Thoughts:
**Analyzing the Page Collapse Logic**

Alright, let's break this down. I'm looking at the `collapse_scan_anon` function, specifically that `find_pmd_or_thp_or_none` call. The crucial point here is that if `result` isn't `SCAN_SUCCEED` after that call – meaning it encountered something that stopped the scan – it jumps to `out;` and the whole function returns that non-success `result`.  Before continuing, `collapse_scan_reset(cc)` is called, so whatever "state" that scan had is properly reset.

Now, considering `collapse_single_pmd`... it *only* calls `collapse_scan_pmd` if the initial `result` was either `SCAN_SUCCEED` or `SCAN_PTE_MAPPED_HUGEPAGE`. That's important. It's a key condition. This indicates the primary collapse scan only happens if something substantial was found that was either a hugepage or a PMD which might then need to be collapsed.

Thinking about both the anonymous and file paths... for the anon case, the only way `result` can be `SCAN_SUCCEED` is if it went through the whole scan loop. That means `collapse_scan_reset(cc)` was called at some point, and at the end of the anon path, the scan counters like `scan_orders`, `scan_referenced`, `scan_unmapped`, as well as `eligible_ptes`, `node_load`, and `alloc_nmask` are all initialized and updated. These are all *set* before `collapse_pmd` which then calls `collapse_anon`.

Hold on... I need to consider the file scan. Let's dig into the `collapse_scan_file` function, lines 2675-2740. This is the piece that's missing from the full picture.



34/3 2026/10/14 23:16 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 2675,
  "LineCount": 40
}

Results:
{
  "Contents": "2675:\t\tXA_STATE(xas, \u0026mapping-\u003ei_pages, start);\n2676:\t\tint present, swap;\n2677:\t\tint node = NUMA_NO_NODE;\n2678:\t\tenum scan_result result = SCAN_SUCCEED;\n2679:\t\tunsigned long failed_pfn = -1;\n2680:\t\n2681:\t\tpresent = 0;\n2682:\t\tswap = 0;\n2683:\t\tcollapse_scan_reset(cc);\n2684:\t\trcu_read_lock();\n2685:\t\txas_for_each(\u0026xas, folio, start + HPAGE_PMD_NR - 1) {\n2686:\t\t\tif (xas_retry(\u0026xas, folio))\n2687:\t\t\t\tcontinue;\n2688:\t\n2689:\t\t\tif (xa_is_value(folio)) {\n2690:\t\t\t\tswap += 1 \u003c\u003c xas_get_order(\u0026xas);\n2691:\t\t\t\tif (swap \u003e max_ptes_swap) {\n2692:\t\t\t\t\tresult = SCAN_EXCEED_SWAP_PTE;\n2693:\t\t\t\t\tcount_vm_event(THP_SCAN_EXCEED_SWAP_PTE);\n2694:\t\t\t\t\tbreak;\n2695:\t\t\t\t}\n2696:\t\t\t\tcontinue;\n2697:\t\t\t}\n2698:\t\n2699:\t\t\tif (!folio_try_get(folio)) {\n2700:\t\t\t\txas_reset(\u0026xas);\n2701:\t\t\t\tcontinue;\n2702:\t\t\t}\n2703:\t\n2704:\t\t\tif (unlikely(folio != xas_reload(\u0026xas))) {\n2705:\t\t\t\tfolio_put(folio);\n2706:\t\t\t\txas_reset(\u0026xas);\n2707:\t\t\t\tcontinue;\n2708:\t\t\t}\n2709:\t\n2710:\t\t\tif (is_pmd_order(folio_order(folio))) {\n2711:\t\t\t\tresult = SCAN_PTE_MAPPED_HUGEPAGE;\n2712:\t\t\t\tfailed_pfn = folio_pfn(folio);\n2713:\t\t\t\t/*\n2714:\t\t\t\t * PMD-sized THP implies that we can only try\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 32222
							output: 37
							thoughts: 378
						

Thoughts:
**My Analysis of the Collapse Scan Process**

Okay, so I'm diving into the `collapse_scan_file` function and the first thing that jumps out is that `collapse_scan_reset(cc)` gets called right at the start. That's good housekeeping, making sure everything's initialized. Now, let's trace the logic. If `result == SCAN_PTE_MAPPED_HUGEPAGE`, I see a clear path. We grab the physical page frame number, then `collapse_scan_pmd` is invoked, which cleverly sets up the context (`cc`) with the file and page offset from the VM area (`vma`). Crucially, in `collapse_pmd` when `SCAN_PTE_MAPPED_HUGEPAGE` is encountered, it skips directly to the `put:` label. This means it bypasses `collapse_file`, calls `fput(file)` to release the file, and proceeds directly to `try_collapse_pte_mapped_thp`. That's an optimization; if we already *know* the hugepage is mapped, no need to do file-specific collapsing.

But, what if `result == SCAN_SUCCEED`? Then `collapse_file(mm, addr, file, pgoff, cc)` is called. That's the core of the file-backed hugepage collapsing logic, so I need to understand it in detail. Let's look up `collapse_file` function in `mm/khugepaged.c` (lines 2600-2640), and see how it handles the file-backed case.



36/3 2026/10/14 23:16 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 2600,
  "LineCount": 40
}

Results:
{
  "Contents": "2600:\t\tfolio_mark_uptodate(new_folio);\n2601:\t\tfolio_ref_add(new_folio, HPAGE_PMD_NR - 1);\n2602:\t\n2603:\t\tif (is_shmem)\n2604:\t\t\tfolio_mark_dirty(new_folio);\n2605:\t\tfolio_add_lru(new_folio);\n2606:\t\n2607:\t\t/* Join all the small entries into a single multi-index entry. */\n2608:\t\txas_set_order(\u0026xas, start, HPAGE_PMD_ORDER);\n2609:\t\txas_store(\u0026xas, new_folio);\n2610:\t\tWARN_ON_ONCE(xas_error(\u0026xas));\n2611:\t\txas_unlock_irq(\u0026xas);\n2612:\t\n2613:\t\t/*\n2614:\t\t * Remove pte page tables, so we can re-fault the page as huge.  A\n2615:\t\t * caller that wants the PMD mapped now is told to go and do that.\n2616:\t\t */\n2617:\t\tretract_page_tables(mapping, start);\n2618:\t\tif (cc-\u003epolicy.file_install_pmd)\n2619:\t\t\tresult = SCAN_PTE_MAPPED_HUGEPAGE;\n2620:\t\tfolio_unlock(new_folio);\n2621:\t\n2622:\t\t/*\n2623:\t\t * The collapse has succeeded, so free the old folios.\n2624:\t\t */\n2625:\t\tlist_for_each_entry_safe(folio, tmp, \u0026pagelist, lru) {\n2626:\t\t\tlist_del(\u0026folio-\u003elru);\n2627:\t\t\tlruvec_stat_mod_folio(folio, NR_FILE_PAGES,\n2628:\t\t\t\t\t      -folio_nr_pages(folio));\n2629:\t\t\tif (is_shmem)\n2630:\t\t\t\tlruvec_stat_mod_folio(folio, NR_SHMEM,\n2631:\t\t\t\t\t\t      -folio_nr_pages(folio));\n2632:\t\t\tfolio-\u003emapping = NULL;\n2633:\t\t\tfolio_clear_active(folio);\n2634:\t\t\tfolio_clear_unevictable(folio);\n2635:\t\t\tfolio_unlock(folio);\n2636:\t\t\tfolio_put_refs(folio, 2 + folio_nr_pages(folio));\n2637:\t\t}\n2638:\t\n2639:\t\tgoto out;\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 33651
							output: 34
							thoughts: 63
						

Thoughts:
**Investigating `alloc_charge_folio` in `collapse_file`**

Okay, let's dive into this. I need to understand how `alloc_charge_folio` is being used within the `collapse_file` function. My first step is to trace the calls. I'm going to quickly search for instances of `alloc_charge_folio` directly within the `collapse_file` code. If that doesn't immediately yield the answer, my next stop will be to broaden the search. I'll check `mm/khugepaged.c` as a likely spot for related functionality. That's a good place to start, given the nature of the operations we're discussing. Hopefully, that will provide the context I need.



38/3 2026/10/14 23:16 tool grepper
0m Args:
{
  "Expression": "alloc_charge_folio",
  "PathPrefixes": [
    "mm/khugepaged.c"
  ]
}

Results:
{
  "Output": "mm/khugepaged.c=1111=static enum scan_result __collapse_huge_page_swapin(struct mm_struct *mm,\n--\nmm/khugepaged.c-1201-\nmm/khugepaged.c:1202:static enum scan_result alloc_charge_folio(struct folio **foliop, struct mm_struct *mm,\nmm/khugepaged.c-1203-\t\tstruct collapse_control *cc, unsigned int order)\n--\nmm/khugepaged.c=1255=static enum scan_result collapse_huge_page(struct mm_struct *mm,\n--\nmm/khugepaged.c-1271-\nmm/khugepaged.c:1272:\tresult = alloc_charge_folio(\u0026folio, mm, cc, order);\nmm/khugepaged.c-1273-\tif (result != SCAN_SUCCEED)\n--\nmm/khugepaged.c=2229=static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,\n--\nmm/khugepaged.c-2251-\nmm/khugepaged.c:2252:\tresult = alloc_charge_folio(\u0026new_folio, mm, cc, HPAGE_PMD_ORDER);\nmm/khugepaged.c-2253-\tif (result != SCAN_SUCCEED)\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 34270
							output: 40
							thoughts: 1200
						

Thoughts:
**Analyzing Potential Uninitialized Reads in Khugepaged**

Okay, let's break this down systematically. I'm focusing on potential uninitialized read scenarios within the khugepaged collapse process. The initial thought goes to checking the allocation function `alloc_charge_folio`.  I see that allocation parameters are reset in `collapse_scan_file` and `collapse_scan_anon`, so that's good.

My next line of thinking focuses on `scan_file` and `scan_pgoff`. Specifically, can these be read before being initialized? I see that in `collapse_control_init`, `cc->scan_file` is initialized to NULL. Then, looking at `collapse_pmd`, the code checks `!file` and returns `collapse_anon`. Only if `file` is set, does `cc->scan_pgoff` get read. Importantly, both `scan_file` and `scan_pgoff` are set *together* later when scanning a file VMA. So the initial concern seems unfounded. They are set together so a read before initialization isn't possible.

Now, I'm shifting to `scan_orders`, `scan_referenced`, and `scan_unmapped`. These are also members of the `collapse_control` structure. I am tracking where they are read. I find that these variables are used inside `collapse_anon` and `collapse_huge_page`. My next thought is, where are they written? Looking inside `collapse_scan_anon`, these variables are *set* only if the function returns `SCAN_SUCCEED`. So, the question becomes, what happens if the result isn't `SCAN_SUCCEED`?

I trace the return values. If `collapse_scan_anon` returns a non-`SCAN_SUCCEED` result, that same result is returned by `collapse_scan_pmd`. Then that result is returned immediately by `collapse_single_pmd`. This means `collapse_pmd` is *never* called, so that section will never be entered, and so there is no potential for an uninitialized read inside that portion of the code. Therefore, `scan_orders`, `scan_referenced`, and `scan_unmapped` are *always* initialized before `collapse_anon` is entered.

The next consideration is if `collapse_scan_anon` can return `SCAN_PTE_MAPPED_HUGEPAGE`, since this would bypass the initial path. I need to investigate where this value might be returned and how it impacts the other code paths. I need to look for calls to `collapse_scan_anon` to trace this behavior.



40/3 2026/10/14 23:16 tool grepper
0m Args:
{
  "Expression": "SCAN_PTE_MAPPED_HUGEPAGE",
  "PathPrefixes": [
    "mm/khugepaged.c"
  ]
}

Results:
{
  "Output": "mm/khugepaged.c=596=static enum scan_result __collapse_huge_page_isolate(struct vm_area_struct *vma,\n--\nmm/khugepaged.c-668-\t\tif (!is_pmd_order(order) \u0026\u0026 folio_order(folio) \u003e= order) {\nmm/khugepaged.c:669:\t\t\tresult = SCAN_PTE_MAPPED_HUGEPAGE;\nmm/khugepaged.c-670-\t\t\tgoto out;\n--\nmm/khugepaged.c=1479=static enum scan_result collapse_anon(struct mm_struct *mm,\n--\nmm/khugepaged.c-1518-\t\t\t\tfallthrough;\nmm/khugepaged.c:1519:\t\t\tcase SCAN_PTE_MAPPED_HUGEPAGE:\nmm/khugepaged.c-1520-\t\t\t\tgoto next_offset;\n--\nmm/khugepaged.c=2229=static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,\n--\nmm/khugepaged.c-2384-\t\tif (is_pmd_order(folio_order(folio))) {\nmm/khugepaged.c:2385:\t\t\tresult = SCAN_PTE_MAPPED_HUGEPAGE;\nmm/khugepaged.c-2386-\t\t\tgoto out_unlock;\n--\nmm/khugepaged.c-2618-\tif (cc-\u003epolicy.file_install_pmd)\nmm/khugepaged.c:2619:\t\tresult = SCAN_PTE_MAPPED_HUGEPAGE;\nmm/khugepaged.c-2620-\tfolio_unlock(new_folio);\n--\nmm/khugepaged.c=2667=static enum scan_result collapse_scan_file(struct mm_struct *mm,\n--\nmm/khugepaged.c-2710-\t\tif (is_pmd_order(folio_order(folio))) {\nmm/khugepaged.c:2711:\t\t\tresult = SCAN_PTE_MAPPED_HUGEPAGE;\nmm/khugepaged.c-2712-\t\t\tfailed_pfn = folio_pfn(folio);\n--\nmm/khugepaged.c-2759-\trcu_read_unlock();\nmm/khugepaged.c:2760:\tif (result == SCAN_PTE_MAPPED_HUGEPAGE)\nmm/khugepaged.c-2761-\t\tcc-\u003eprogress++;\n--\nmm/khugepaged.c=2781=static enum scan_result collapse_scan_pmd(struct vm_area_struct *vma,\n--\nmm/khugepaged.c-2799-\t/*\nmm/khugepaged.c:2800:\t * SCAN_PTE_MAPPED_HUGEPAGE is work too: the page cache already holds\nmm/khugepaged.c-2801-\t * the PMD folio, and collapse_pmd() still has to retract the PTE table.\nmm/khugepaged.c-2802-\t */\nmm/khugepaged.c:2803:\tif (result != SCAN_SUCCEED \u0026\u0026 result != SCAN_PTE_MAPPED_HUGEPAGE)\nmm/khugepaged.c-2804-\t\treturn result;\n--\nmm/khugepaged.c=2815=static enum scan_result collapse_pmd(struct mm_struct *mm,\n--\nmm/khugepaged.c-2829-\t/* The scan found the PMD folio in place: nothing to collapse */\nmm/khugepaged.c:2830:\tif (result == SCAN_PTE_MAPPED_HUGEPAGE)\nmm/khugepaged.c-2831-\t\tgoto put;\n--\nmm/khugepaged.c-2851-\t */\nmm/khugepaged.c:2852:\tif (result == SCAN_PTE_MAPPED_HUGEPAGE) {\nmm/khugepaged.c-2853-\t\tmmap_read_lock(mm);\n--\nmm/khugepaged.c=2870=static enum scan_result collapse_single_pmd(unsigned long addr,\n--\nmm/khugepaged.c-2877-\tresult = collapse_scan_pmd(vma, addr, cc);\nmm/khugepaged.c:2878:\tif (result != SCAN_SUCCEED \u0026\u0026 result != SCAN_PTE_MAPPED_HUGEPAGE)\nmm/khugepaged.c-2879-\t\treturn result;\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 37257
							output: 37
							thoughts: 52
						

Thoughts:
Okay, let's see.

**Analyzing `collapse_scan_anon`'s Return Value**

Hmm, interesting. I've got a situation here, and my initial thought is: Look at that! Is it possible for `collapse_scan_anon` to actually return `SCAN_PTE_MAPPED_HUGEPAGE`? That seems like a key question.

To figure this out definitively, I need to dig into the code and quickly confirm. Right, let me check lines 1620 through 1770 within the `collapse_scan_anon` function. That section should give me the specifics I'm looking for regarding the possible return values under various conditions. Let's see what's actually going on in there.



42/3 2026/10/14 23:16 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 1620,
  "LineCount": 80
}

Results:
{
  "Contents": "1620:\t\tpte = pte_offset_map_lock(mm, pmd, start_addr, \u0026ptl);\n1621:\t\tif (!pte) {\n1622:\t\t\tcc-\u003eprogress++;\n1623:\t\t\tresult = SCAN_NO_PTE_TABLE;\n1624:\t\t\tgoto out;\n1625:\t\t}\n1626:\t\n1627:\t\tfor (i = 0; i \u003c HPAGE_PMD_NR; i++) {\n1628:\t\t\t_pte = pte + i;\n1629:\t\t\taddr = start_addr + i * PAGE_SIZE;\n1630:\t\t\tpteval = ptep_get(_pte);\n1631:\t\n1632:\t\t\tcc-\u003eprogress++;\n1633:\t\n1634:\t\t\tif (pte_none_or_zero(pteval)) {\n1635:\t\t\t\tif (++none_or_zero \u003e max_ptes_none) {\n1636:\t\t\t\t\tresult = SCAN_EXCEED_NONE_PTE;\n1637:\t\t\t\t\tcount_collapse_event(HPAGE_PMD_ORDER, THP_SCAN_EXCEED_NONE_PTE,\n1638:\t\t\t\t\t\t\t     MTHP_STAT_COLLAPSE_EXCEED_NONE);\n1639:\t\t\t\t\tgoto out_unmap;\n1640:\t\t\t\t}\n1641:\t\t\t\tcontinue;\n1642:\t\t\t}\n1643:\t\t\tif (!pte_present(pteval)) {\n1644:\t\t\t\tif (++unmapped \u003e max_ptes_swap) {\n1645:\t\t\t\t\tresult = SCAN_EXCEED_SWAP_PTE;\n1646:\t\t\t\t\tcount_collapse_event(HPAGE_PMD_ORDER, THP_SCAN_EXCEED_SWAP_PTE,\n1647:\t\t\t\t\t\t\t     MTHP_STAT_COLLAPSE_EXCEED_SWAP);\n1648:\t\t\t\t\tgoto out_unmap;\n1649:\t\t\t\t}\n1650:\t\t\t\t/*\n1651:\t\t\t\t * Always be strict with uffd-wp\n1652:\t\t\t\t * enabled swap entries.  Please see\n1653:\t\t\t\t * comment below for pte_uffd().\n1654:\t\t\t\t */\n1655:\t\t\t\tif (pte_swp_uffd_any(pteval)) {\n1656:\t\t\t\t\tresult = SCAN_PTE_UFFD;\n1657:\t\t\t\t\tgoto out_unmap;\n1658:\t\t\t\t}\n1659:\t\t\t\tcontinue;\n1660:\t\t\t}\n1661:\t\t\tif (pte_uffd(pteval)) {\n1662:\t\t\t\t/*\n1663:\t\t\t\t * Don't collapse the page if any of the small\n1664:\t\t\t\t * PTEs are armed with uffd write protection.\n1665:\t\t\t\t * Here we can also mark the new huge pmd as\n1666:\t\t\t\t * write protected if any of the small ones is\n1667:\t\t\t\t * marked but that could bring unknown\n1668:\t\t\t\t * userfault messages that falls outside of\n1669:\t\t\t\t * the registered range.  So, just be simple.\n1670:\t\t\t\t */\n1671:\t\t\t\tresult = SCAN_PTE_UFFD;\n1672:\t\t\t\tgoto out_unmap;\n1673:\t\t\t}\n1674:\t\n1675:\t\t\tpage = vm_normal_page(vma, addr, pteval);\n1676:\t\t\tif (unlikely(!page) || unlikely(is_zone_device_page(page))) {\n1677:\t\t\t\tresult = SCAN_PAGE_NULL;\n1678:\t\t\t\tgoto out_unmap;\n1679:\t\t\t}\n1680:\t\t\tfolio = page_folio(page);\n1681:\t\n1682:\t\t\t/*\n1683:\t\t\t * If the vma has the VM_DROPPABLE flag, the collapse will\n1684:\t\t\t * preserve the lazyfree property without needing to skip.\n1685:\t\t\t */\n1686:\t\t\tif (cc-\u003epolicy.anon_skip_lazyfree \u0026\u0026 !(vma-\u003evm_flags \u0026 VM_DROPPABLE) \u0026\u0026\n1687:\t\t\t    folio_test_lazyfree(folio) \u0026\u0026 !pte_dirty(pteval)) {\n1688:\t\t\t\tresult = SCAN_PAGE_LAZYFREE;\n1689:\t\t\t\tfailed_pfn = folio_pfn(folio);\n1690:\t\t\t\tgoto out_unmap;\n1691:\t\t\t}\n1692:\t\n1693:\t\t\tif (!folio_test_anon(folio)) {\n1694:\t\t\t\tresult = SCAN_PAGE_ANON;\n1695:\t\t\t\tfailed_pfn = folio_pfn(folio);\n1696:\t\t\t\tgoto out_unmap;\n1697:\t\t\t}\n1698:\t\n1699:\t\t\t/*\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 38741
							output: 37
							thoughts: 26
						

Thoughts:
Okay, here's my take on those lines in `collapse_scan_anon`, as though they represent my own thought process:

**Diving into `collapse_scan_anon` - Lines 1700-1770**

Alright, let's zoom in on that section of `collapse_scan_anon`, specifically lines 1700 to 1770. I'm going to have to carefully consider the logic around this section. I'm especially interested in understanding the data transformation and filtering in this region. I suspect the function is designed to handle very specific cases or scenarios, perhaps with edge cases, given the density of logic I'm seeing. This is probably a good place to start my investigation.



44/3 2026/10/14 23:16 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 1700,
  "LineCount": 70
}

Results:
{
  "Contents": "1700:\t\t\t * We treat a single page as shared if any part of the THP\n1701:\t\t\t * is shared.\n1702:\t\t\t */\n1703:\t\t\tif (folio_maybe_mapped_shared(folio)) {\n1704:\t\t\t\tif (++shared \u003e max_ptes_shared) {\n1705:\t\t\t\t\tresult = SCAN_EXCEED_SHARED_PTE;\n1706:\t\t\t\t\tfailed_pfn = folio_pfn(folio);\n1707:\t\t\t\t\tcount_collapse_event(HPAGE_PMD_ORDER, THP_SCAN_EXCEED_SHARED_PTE,\n1708:\t\t\t\t\t\t\t     MTHP_STAT_COLLAPSE_EXCEED_SHARED);\n1709:\t\t\t\t\tgoto out_unmap;\n1710:\t\t\t\t}\n1711:\t\t\t}\n1712:\t\n1713:\t\t\t/* The scan accepted this PTE as a collapse source */\n1714:\t\t\t__set_bit(i, cc-\u003eeligible_ptes);\n1715:\t\t\t/*\n1716:\t\t\t * Record which node the original page is from and save this\n1717:\t\t\t * information to cc-\u003enode_load[].\n1718:\t\t\t * Khugepaged will allocate hugepage from the node has the max\n1719:\t\t\t * hit record.\n1720:\t\t\t */\n1721:\t\t\tnode = folio_nid(folio);\n1722:\t\t\tif (collapse_scan_abort(node, cc)) {\n1723:\t\t\t\tresult = SCAN_SCAN_ABORT;\n1724:\t\t\t\tfailed_pfn = folio_pfn(folio);\n1725:\t\t\t\tgoto out_unmap;\n1726:\t\t\t}\n1727:\t\t\tcc-\u003enode_load[node]++;\n1728:\t\t\tif (!folio_test_lru(folio)) {\n1729:\t\t\t\tresult = SCAN_PAGE_LRU;\n1730:\t\t\t\tfailed_pfn = folio_pfn(folio);\n1731:\t\t\t\tgoto out_unmap;\n1732:\t\t\t}\n1733:\t\t\tif (folio_test_locked(folio)) {\n1734:\t\t\t\tresult = SCAN_PAGE_LOCK;\n1735:\t\t\t\tfailed_pfn = folio_pfn(folio);\n1736:\t\t\t\tgoto out_unmap;\n1737:\t\t\t}\n1738:\t\n1739:\t\t\t/*\n1740:\t\t\t * Check if the page has any GUP (or other external) pins.\n1741:\t\t\t *\n1742:\t\t\t * Here the check is racy, but such cases are ephemeral and\n1743:\t\t\t * we can always retry collapse later. Anyway the same\n1744:\t\t\t * check will be done again later, so the risk seems to be low.\n1745:\t\t\t */\n1746:\t\t\tif (folio_expected_ref_count(folio) != folio_ref_count(folio)) {\n1747:\t\t\t\tresult = SCAN_PAGE_COUNT;\n1748:\t\t\t\tfailed_pfn = folio_pfn(folio);\n1749:\t\t\t\tgoto out_unmap;\n1750:\t\t\t}\n1751:\t\n1752:\t\t\tif (cc-\u003epolicy.anon_require_referenced \u0026\u0026\n1753:\t\t\t    folio_pte_referenced(folio, vma, addr, pteval))\n1754:\t\t\t\treferenced++;\n1755:\t\t}\n1756:\t\tif (cc-\u003epolicy.anon_require_referenced \u0026\u0026\n1757:\t\t    (!referenced ||\n1758:\t\t     (unmapped \u0026\u0026 referenced \u003c HPAGE_PMD_NR / 2))) {\n1759:\t\t\tresult = SCAN_LACK_REFERENCED_PAGE;\n1760:\t\t} else {\n1761:\t\t\tresult = SCAN_SUCCEED;\n1762:\t\t}\n1763:\tout_unmap:\n1764:\t\tpte_unmap_unlock(pte, ptl);\n1765:\t\tif (result == SCAN_SUCCEED) {\n1766:\t\t\tcc-\u003escan_orders = enabled_orders;\n1767:\t\t\tcc-\u003escan_referenced = referenced;\n1768:\t\t\tcc-\u003escan_unmapped = unmapped;\n1769:\t\t}\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 40045
							output: 31
							thoughts: 299
						

Thoughts:
**Analyzing the `collapse_scan_anon` Function**

Okay, so I'm digging into this `collapse_scan_anon` function, and it's striking me that it **never** returns `SCAN_PTE_MAPPED_HUGEPAGE`. That's a fundamental aspect. It can only return one of these specific codes: `SCAN_SUCCEED`, `SCAN_NO_PTE_TABLE`, `SCAN_EXCEED_NONE_PTE`, `SCAN_EXCEED_SWAP_PTE`, `SCAN_PTE_UFFD`, `SCAN_PAGE_NULL`, `SCAN_PAGE_LAZYFREE`, `SCAN_PAGE_ANON`, `SCAN_EXCEED_SHARED_PTE`, `SCAN_SCAN_ABORT`, `SCAN_PAGE_LRU`, `SCAN_PAGE_LOCK`, `SCAN_PAGE_COUNT`, or `SCAN_LACK_REFERENCED_PAGE`.

This is crucial because it means `collapse_pmd` is only triggered when the result is `SCAN_SUCCEED`. And because of that, if the function returns `SCAN_SUCCEED`, then `cc->scan_orders`, `cc->scan_referenced`, and `cc->scan_unmapped` are *always* initialized right before the function exits. I need to make sure this is consistent throughout the code and that I understand the implications fully.

Let's double-check this, just to be thorough, I need to make sure there aren't any edge cases I'm missing. Are there any other places in `mm/khugepaged.c` where `collapse_control` or `collapse_policy` are used? I should also check every instance where `cc->` is used to make sure I'm not missing anything. I think the best approach is to grep the file for all uses of `cc->`. That will give me the most complete picture.



46/3 2026/10/14 23:16 tool grepper
0m Args:
{
  "Expression": "cc-\u003e",
  "PathPrefixes": [
    "mm/khugepaged.c"
  ]
}

Results:
{
  "Output": "\nFull output is too long, showing 200 out of 271 lines.\nUse more precise expression or PathPrefixes if possible.\n\nNumber of matching lines per file (1 files in total):\nmm/khugepaged.c:69\n\nmm/khugepaged.c=314=static unsigned int collapse_max_ptes_none(struct collapse_control *cc,\n--\nmm/khugepaged.c-321-\tif (is_pmd_order(order))\nmm/khugepaged.c:322:\t\treturn cc-\u003epolicy.pmd.max_ptes_none;\nmm/khugepaged.c-323-\nmm/khugepaged.c-324-\t/* Below PMD order: all but one PTE of the window, or none */\nmm/khugepaged.c:325:\tmax_ptes_none = cc-\u003epolicy.sub_pmd.max_ptes_none;\nmm/khugepaged.c-326-\tif (max_ptes_none == COLLAPSE_MAX_PTES_LIMIT)\n--\nmm/khugepaged.c=340=static unsigned int collapse_max_ptes_shared(struct collapse_control *cc,\n--\nmm/khugepaged.c-343-\tif (is_pmd_order(order))\nmm/khugepaged.c:344:\t\treturn cc-\u003epolicy.pmd.max_ptes_shared;\nmm/khugepaged.c:345:\treturn cc-\u003epolicy.sub_pmd.max_ptes_shared;\nmm/khugepaged.c-346-}\n--\nmm/khugepaged.c=357=static unsigned int collapse_max_ptes_swap(struct collapse_control *cc,\n--\nmm/khugepaged.c-360-\tif (is_pmd_order(order))\nmm/khugepaged.c:361:\t\treturn cc-\u003epolicy.pmd.max_ptes_swap;\nmm/khugepaged.c:362:\treturn cc-\u003epolicy.sub_pmd.max_ptes_swap;\nmm/khugepaged.c-363-}\n--\nmm/khugepaged.c=535=static void collapse_scan_reset(struct collapse_control *cc)\nmm/khugepaged.c-536-{\nmm/khugepaged.c:537:\tmemset(cc-\u003enode_load, 0, sizeof(cc-\u003enode_load));\nmm/khugepaged.c:538:\tnodes_clear(cc-\u003ealloc_nmask);\nmm/khugepaged.c:539:\tbitmap_zero(cc-\u003eeligible_ptes, MAX_PTRS_PER_PTE);\nmm/khugepaged.c-540-}\n--\nmm/khugepaged.c=596=static enum scan_result __collapse_huge_page_isolate(struct vm_area_struct *vma,\n--\nmm/khugepaged.c-642-\t\t */\nmm/khugepaged.c:643:\t\tif (cc-\u003epolicy.anon_skip_lazyfree \u0026\u0026 !(vma-\u003evm_flags \u0026 VM_DROPPABLE) \u0026\u0026\nmm/khugepaged.c-644-\t\t    folio_test_lazyfree(folio) \u0026\u0026 !pte_dirty(pteval)) {\n--\nmm/khugepaged.c-731-next:\nmm/khugepaged.c:732:\t\tif (cc-\u003epolicy.anon_require_referenced \u0026\u0026\nmm/khugepaged.c-733-\t\t    folio_pte_referenced(folio, vma, addr, pteval))\n--\nmm/khugepaged.c-736-\nmm/khugepaged.c:737:\tif (unlikely(cc-\u003epolicy.anon_require_referenced \u0026\u0026 !referenced)) {\nmm/khugepaged.c-738-\t\tresult = SCAN_LACK_REFERENCED_PAGE;\n--\nmm/khugepaged.c=905=static bool collapse_scan_abort(int nid, struct collapse_control *cc)\n--\nmm/khugepaged.c-916-\t/* If there is a count for this node already, it must be acceptable */\nmm/khugepaged.c:917:\tif (cc-\u003enode_load[nid])\nmm/khugepaged.c-918-\t\treturn false;\n--\nmm/khugepaged.c-920-\tfor (i = 0; i \u003c MAX_NUMNODES; i++) {\nmm/khugepaged.c:921:\t\tif (!cc-\u003enode_load[i])\nmm/khugepaged.c-922-\t\t\tcontinue;\n--\nmm/khugepaged.c=986=static int collapse_find_target_node(struct collapse_control *cc)\n--\nmm/khugepaged.c-991-\tfor (nid = 0; nid \u003c MAX_NUMNODES; nid++)\nmm/khugepaged.c:992:\t\tif (cc-\u003enode_load[nid] \u003e max_value) {\nmm/khugepaged.c:993:\t\t\tmax_value = cc-\u003enode_load[nid];\nmm/khugepaged.c-994-\t\t\ttarget_node = nid;\n--\nmm/khugepaged.c-997-\tfor_each_online_node(nid) {\nmm/khugepaged.c:998:\t\tif (max_value == cc-\u003enode_load[nid])\nmm/khugepaged.c:999:\t\t\tnode_set(nid, cc-\u003ealloc_nmask);\nmm/khugepaged.c-1000-\t}\n--\nmm/khugepaged.c=1017=static enum scan_result hugepage_vma_revalidate(struct mm_struct *mm, unsigned long address,\n--\nmm/khugepaged.c-1021-\tstruct vm_area_struct *vma;\nmm/khugepaged.c:1022:\tenum tva_type type = cc-\u003epolicy.tva_type;\nmm/khugepaged.c-1023-\n--\nmm/khugepaged.c=1202=static enum scan_result alloc_charge_folio(struct folio **foliop, struct mm_struct *mm,\n--\nmm/khugepaged.c-1204-{\nmm/khugepaged.c:1205:\tgfp_t gfp = cc-\u003epolicy.gfp;\nmm/khugepaged.c-1206-\tint node = collapse_find_target_node(cc);\n--\nmm/khugepaged.c-1208-\nmm/khugepaged.c:1209:\tfolio = __folio_alloc(gfp, order, node, \u0026cc-\u003ealloc_nmask);\nmm/khugepaged.c-1210-\tif (!folio) {\n--\nmm/khugepaged.c=1255=static enum scan_result collapse_huge_page(struct mm_struct *mm,\n--\nmm/khugepaged.c-1302-\nmm/khugepaged.c:1303:\tif (cc-\u003escan_unmapped) {\nmm/khugepaged.c-1304-\t\t/*\n--\nmm/khugepaged.c-1309-\t\tresult = __collapse_huge_page_swapin(mm, vma, start_addr, pmd,\nmm/khugepaged.c:1310:\t\t\t\t\t\t     cc-\u003escan_referenced, order);\nmm/khugepaged.c-1311-\t\tif (result != SCAN_SUCCEED)\n--\nmm/khugepaged.c=1454=static unsigned int max_order_from_offset(unsigned int offset)\n--\nmm/khugepaged.c-1465- *\nmm/khugepaged.c:1466: * Each bit in cc-\u003eeligible_ptes marks a PTE the scan accepted as a collapse\nmm/khugepaged.c-1467- * source. We start at the PMD order and check if it is eligible for collapse;\n--\nmm/khugepaged.c=1479=static enum scan_result collapse_anon(struct mm_struct *mm,\n--\nmm/khugepaged.c-1492-\nmm/khugepaged.c:1493:\t\tif (!test_bit(order, \u0026cc-\u003escan_orders))\nmm/khugepaged.c-1494-\t\t\tgoto next_order;\n--\nmm/khugepaged.c-1496-\t\tmax_ptes_none = collapse_max_ptes_none(cc, NULL, order);\nmm/khugepaged.c:1497:\t\tnr_eligible_ptes = bitmap_weight_from(cc-\u003eeligible_ptes, offset,\nmm/khugepaged.c-1498-\t\t\t\t\t\t      offset + nr_ptes);\n--\nmm/khugepaged.c-1501-\t\t * Swap PTEs accepted during the scan are counted in\nmm/khugepaged.c:1502:\t\t * cc-\u003escan_unmapped, not in cc-\u003eeligible_ptes. Account them for\nmm/khugepaged.c-1503-\t\t * the PMD-order candidate.\n--\nmm/khugepaged.c-1505-\t\tif (is_pmd_order(order))\nmm/khugepaged.c:1506:\t\t\tnr_eligible_ptes += cc-\u003escan_unmapped;\nmm/khugepaged.c-1507-\n--\nmm/khugepaged.c-1553-\t\tif (order \u003e COLLAPSE_MIN_MTHP_ORDER \u0026\u0026\nmm/khugepaged.c:1554:\t\t    (cc-\u003escan_orders \u0026 GENMASK(order - 1, 0))) {\nmm/khugepaged.c-1555-\t\t\torder--;\n--\nmm/khugepaged.c=1579=static enum scan_result collapse_scan_anon(struct vm_area_struct *vma,\n--\nmm/khugepaged.c-1584-\tunsigned int max_ptes_none = collapse_max_ptes_none(cc, vma, HPAGE_PMD_ORDER);\nmm/khugepaged.c:1585:\tenum tva_type tva_flags = cc-\u003epolicy.tva_type;\nmm/khugepaged.c-1586-\tstruct mm_struct *mm = vma-\u003evm_mm;\n--\nmm/khugepaged.c-1603-\tif (result != SCAN_SUCCEED) {\nmm/khugepaged.c:1604:\t\tcc-\u003eprogress++;\nmm/khugepaged.c-1605-\t\tgoto out;\n--\nmm/khugepaged.c-1621-\tif (!pte) {\nmm/khugepaged.c:1622:\t\tcc-\u003eprogress++;\nmm/khugepaged.c-1623-\t\tresult = SCAN_NO_PTE_TABLE;\n--\nmm/khugepaged.c-1631-\nmm/khugepaged.c:1632:\t\tcc-\u003eprogress++;\nmm/khugepaged.c-1633-\n--\nmm/khugepaged.c-1685-\t\t */\nmm/khugepaged.c:1686:\t\tif (cc-\u003epolicy.anon_skip_lazyfree \u0026\u0026 !(vma-\u003evm_flags \u0026 VM_DROPPABLE) \u0026\u0026\nmm/khugepaged.c-1687-\t\t    folio_test_lazyfree(folio) \u0026\u0026 !pte_dirty(pteval)) {\n--\nmm/khugepaged.c-1713-\t\t/* The scan accepted this PTE as a collapse source */\nmm/khugepaged.c:1714:\t\t__set_bit(i, cc-\u003eeligible_ptes);\nmm/khugepaged.c-1715-\t\t/*\nmm/khugepaged.c-1716-\t\t * Record which node the original page is from and save this\nmm/khugepaged.c:1717:\t\t * information to cc-\u003enode_load[].\nmm/khugepaged.c-1718-\t\t * Khugepaged will allocate hugepage from the node has the max\n--\nmm/khugepaged.c-1726-\t\t}\nmm/khugepaged.c:1727:\t\tcc-\u003enode_load[node]++;\nmm/khugepaged.c-1728-\t\tif (!folio_test_lru(folio)) {\n--\nmm/khugepaged.c-1751-\nmm/khugepaged.c:1752:\t\tif (cc-\u003epolicy.anon_require_referenced \u0026\u0026\nmm/khugepaged.c-1753-\t\t    folio_pte_referenced(folio, vma, addr, pteval))\n--\nmm/khugepaged.c-1755-\t}\nmm/khugepaged.c:1756:\tif (cc-\u003epolicy.anon_require_referenced \u0026\u0026\nmm/khugepaged.c-1757-\t    (!referenced ||\n--\nmm/khugepaged.c-1765-\tif (result == SCAN_SUCCEED) {\nmm/khugepaged.c:1766:\t\tcc-\u003escan_orders = enabled_orders;\nmm/khugepaged.c:1767:\t\tcc-\u003escan_referenced = referenced;\nmm/khugepaged.c:1768:\t\tcc-\u003escan_unmapped = unmapped;\nmm/khugepaged.c-1769-\t}\n--\nmm/khugepaged.c=2229=static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,\n--\nmm/khugepaged.c-2617-\tretract_page_tables(mapping, start);\nmm/khugepaged.c:2618:\tif (cc-\u003epolicy.file_install_pmd)\nmm/khugepaged.c-2619-\t\tresult = SCAN_PTE_MAPPED_HUGEPAGE;\n--\nmm/khugepaged.c=2667=static enum scan_result collapse_scan_file(struct mm_struct *mm,\n--\nmm/khugepaged.c-2727-\t\t}\nmm/khugepaged.c:2728:\t\tcc-\u003enode_load[node]++;\nmm/khugepaged.c-2729-\n--\nmm/khugepaged.c-2760-\tif (result == SCAN_PTE_MAPPED_HUGEPAGE)\nmm/khugepaged.c:2761:\t\tcc-\u003eprogress++;\nmm/khugepaged.c-2762-\telse\nmm/khugepaged.c:2763:\t\tcc-\u003eprogress += HPAGE_PMD_NR;\nmm/khugepaged.c-2764-\n--\nmm/khugepaged.c=2775=static void collapse_control_init(struct collapse_control *cc)\nmm/khugepaged.c-2776-{\nmm/khugepaged.c:2777:\tcc-\u003eprogress = 0;\nmm/khugepaged.c:2778:\tcc-\u003escan_file = NULL;\nmm/khugepaged.c-2779-}\n--\nmm/khugepaged.c=2781=static enum scan_result collapse_scan_pmd(struct vm_area_struct *vma,\n--\nmm/khugepaged.c-2788-\t/* A scan that found work has to have been followed by collapse_pmd() */\nmm/khugepaged.c:2789:\tif (WARN_ON_ONCE(cc-\u003escan_file)) {\nmm/khugepaged.c:2790:\t\tfput(cc-\u003escan_file);\nmm/khugepaged.c:2791:\t\tcc-\u003escan_file = NULL;\nmm/khugepaged.c-2792-\t}\n--\nmm/khugepaged.c-2809-\t */\n\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 44868
							output: 32
							thoughts: 30
						

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

**Investigating `cc->` in `mm/khugepaged.c`**

Alright, so I've been tracing the usage of `cc->` and I'm down to the tail end of references. My current focus? I need to get a full picture of what this pointer means within `mm/khugepaged.c`. Let's assume that there were other places to check before; now, the real work begins. I'm going to carefully step through the remaining occurrences in the khugepaged file. I'll need to understand the data structures being accessed, the context of the code using the pointer, and any potential side effects. My goal is to determine if there's a pattern to these references. Let's see what interesting tidbits and nuances I can tease out of `mm/khugepaged.c`. I have a feeling this will likely unlock a crucial piece of the puzzle and provide important insight into the overall architecture.



48/3 2026/10/14 23:17 tool grepper
0m Args:
{
  "Expression": "cc-\u003e.*",
  "PathPrefixes": [
    "mm/khugepaged.c"
  ]
}

Results:
{
  "Output": "\nFull output is too long, showing 200 out of 271 lines.\nUse more precise expression or PathPrefixes if possible.\n\nNumber of matching lines per file (1 files in total):\nmm/khugepaged.c:69\n\nmm/khugepaged.c=314=static unsigned int collapse_max_ptes_none(struct collapse_control *cc,\n--\nmm/khugepaged.c-321-\tif (is_pmd_order(order))\nmm/khugepaged.c:322:\t\treturn cc-\u003epolicy.pmd.max_ptes_none;\nmm/khugepaged.c-323-\nmm/khugepaged.c-324-\t/* Below PMD order: all but one PTE of the window, or none */\nmm/khugepaged.c:325:\tmax_ptes_none = cc-\u003epolicy.sub_pmd.max_ptes_none;\nmm/khugepaged.c-326-\tif (max_ptes_none == COLLAPSE_MAX_PTES_LIMIT)\n--\nmm/khugepaged.c=340=static unsigned int collapse_max_ptes_shared(struct collapse_control *cc,\n--\nmm/khugepaged.c-343-\tif (is_pmd_order(order))\nmm/khugepaged.c:344:\t\treturn cc-\u003epolicy.pmd.max_ptes_shared;\nmm/khugepaged.c:345:\treturn cc-\u003epolicy.sub_pmd.max_ptes_shared;\nmm/khugepaged.c-346-}\n--\nmm/khugepaged.c=357=static unsigned int collapse_max_ptes_swap(struct collapse_control *cc,\n--\nmm/khugepaged.c-360-\tif (is_pmd_order(order))\nmm/khugepaged.c:361:\t\treturn cc-\u003epolicy.pmd.max_ptes_swap;\nmm/khugepaged.c:362:\treturn cc-\u003epolicy.sub_pmd.max_ptes_swap;\nmm/khugepaged.c-363-}\n--\nmm/khugepaged.c=535=static void collapse_scan_reset(struct collapse_control *cc)\nmm/khugepaged.c-536-{\nmm/khugepaged.c:537:\tmemset(cc-\u003enode_load, 0, sizeof(cc-\u003enode_load));\nmm/khugepaged.c:538:\tnodes_clear(cc-\u003ealloc_nmask);\nmm/khugepaged.c:539:\tbitmap_zero(cc-\u003eeligible_ptes, MAX_PTRS_PER_PTE);\nmm/khugepaged.c-540-}\n--\nmm/khugepaged.c=596=static enum scan_result __collapse_huge_page_isolate(struct vm_area_struct *vma,\n--\nmm/khugepaged.c-642-\t\t */\nmm/khugepaged.c:643:\t\tif (cc-\u003epolicy.anon_skip_lazyfree \u0026\u0026 !(vma-\u003evm_flags \u0026 VM_DROPPABLE) \u0026\u0026\nmm/khugepaged.c-644-\t\t    folio_test_lazyfree(folio) \u0026\u0026 !pte_dirty(pteval)) {\n--\nmm/khugepaged.c-731-next:\nmm/khugepaged.c:732:\t\tif (cc-\u003epolicy.anon_require_referenced \u0026\u0026\nmm/khugepaged.c-733-\t\t    folio_pte_referenced(folio, vma, addr, pteval))\n--\nmm/khugepaged.c-736-\nmm/khugepaged.c:737:\tif (unlikely(cc-\u003epolicy.anon_require_referenced \u0026\u0026 !referenced)) {\nmm/khugepaged.c-738-\t\tresult = SCAN_LACK_REFERENCED_PAGE;\n--\nmm/khugepaged.c=905=static bool collapse_scan_abort(int nid, struct collapse_control *cc)\n--\nmm/khugepaged.c-916-\t/* If there is a count for this node already, it must be acceptable */\nmm/khugepaged.c:917:\tif (cc-\u003enode_load[nid])\nmm/khugepaged.c-918-\t\treturn false;\n--\nmm/khugepaged.c-920-\tfor (i = 0; i \u003c MAX_NUMNODES; i++) {\nmm/khugepaged.c:921:\t\tif (!cc-\u003enode_load[i])\nmm/khugepaged.c-922-\t\t\tcontinue;\n--\nmm/khugepaged.c=986=static int collapse_find_target_node(struct collapse_control *cc)\n--\nmm/khugepaged.c-991-\tfor (nid = 0; nid \u003c MAX_NUMNODES; nid++)\nmm/khugepaged.c:992:\t\tif (cc-\u003enode_load[nid] \u003e max_value) {\nmm/khugepaged.c:993:\t\t\tmax_value = cc-\u003enode_load[nid];\nmm/khugepaged.c-994-\t\t\ttarget_node = nid;\n--\nmm/khugepaged.c-997-\tfor_each_online_node(nid) {\nmm/khugepaged.c:998:\t\tif (max_value == cc-\u003enode_load[nid])\nmm/khugepaged.c:999:\t\t\tnode_set(nid, cc-\u003ealloc_nmask);\nmm/khugepaged.c-1000-\t}\n--\nmm/khugepaged.c=1017=static enum scan_result hugepage_vma_revalidate(struct mm_struct *mm, unsigned long address,\n--\nmm/khugepaged.c-1021-\tstruct vm_area_struct *vma;\nmm/khugepaged.c:1022:\tenum tva_type type = cc-\u003epolicy.tva_type;\nmm/khugepaged.c-1023-\n--\nmm/khugepaged.c=1202=static enum scan_result alloc_charge_folio(struct folio **foliop, struct mm_struct *mm,\n--\nmm/khugepaged.c-1204-{\nmm/khugepaged.c:1205:\tgfp_t gfp = cc-\u003epolicy.gfp;\nmm/khugepaged.c-1206-\tint node = collapse_find_target_node(cc);\n--\nmm/khugepaged.c-1208-\nmm/khugepaged.c:1209:\tfolio = __folio_alloc(gfp, order, node, \u0026cc-\u003ealloc_nmask);\nmm/khugepaged.c-1210-\tif (!folio) {\n--\nmm/khugepaged.c=1255=static enum scan_result collapse_huge_page(struct mm_struct *mm,\n--\nmm/khugepaged.c-1302-\nmm/khugepaged.c:1303:\tif (cc-\u003escan_unmapped) {\nmm/khugepaged.c-1304-\t\t/*\n--\nmm/khugepaged.c-1309-\t\tresult = __collapse_huge_page_swapin(mm, vma, start_addr, pmd,\nmm/khugepaged.c:1310:\t\t\t\t\t\t     cc-\u003escan_referenced, order);\nmm/khugepaged.c-1311-\t\tif (result != SCAN_SUCCEED)\n--\nmm/khugepaged.c=1454=static unsigned int max_order_from_offset(unsigned int offset)\n--\nmm/khugepaged.c-1465- *\nmm/khugepaged.c:1466: * Each bit in cc-\u003eeligible_ptes marks a PTE the scan accepted as a collapse\nmm/khugepaged.c-1467- * source. We start at the PMD order and check if it is eligible for collapse;\n--\nmm/khugepaged.c=1479=static enum scan_result collapse_anon(struct mm_struct *mm,\n--\nmm/khugepaged.c-1492-\nmm/khugepaged.c:1493:\t\tif (!test_bit(order, \u0026cc-\u003escan_orders))\nmm/khugepaged.c-1494-\t\t\tgoto next_order;\n--\nmm/khugepaged.c-1496-\t\tmax_ptes_none = collapse_max_ptes_none(cc, NULL, order);\nmm/khugepaged.c:1497:\t\tnr_eligible_ptes = bitmap_weight_from(cc-\u003eeligible_ptes, offset,\nmm/khugepaged.c-1498-\t\t\t\t\t\t      offset + nr_ptes);\n--\nmm/khugepaged.c-1501-\t\t * Swap PTEs accepted during the scan are counted in\nmm/khugepaged.c:1502:\t\t * cc-\u003escan_unmapped, not in cc-\u003eeligible_ptes. Account them for\nmm/khugepaged.c-1503-\t\t * the PMD-order candidate.\n--\nmm/khugepaged.c-1505-\t\tif (is_pmd_order(order))\nmm/khugepaged.c:1506:\t\t\tnr_eligible_ptes += cc-\u003escan_unmapped;\nmm/khugepaged.c-1507-\n--\nmm/khugepaged.c-1553-\t\tif (order \u003e COLLAPSE_MIN_MTHP_ORDER \u0026\u0026\nmm/khugepaged.c:1554:\t\t    (cc-\u003escan_orders \u0026 GENMASK(order - 1, 0))) {\nmm/khugepaged.c-1555-\t\t\torder--;\n--\nmm/khugepaged.c=1579=static enum scan_result collapse_scan_anon(struct vm_area_struct *vma,\n--\nmm/khugepaged.c-1584-\tunsigned int max_ptes_none = collapse_max_ptes_none(cc, vma, HPAGE_PMD_ORDER);\nmm/khugepaged.c:1585:\tenum tva_type tva_flags = cc-\u003epolicy.tva_type;\nmm/khugepaged.c-1586-\tstruct mm_struct *mm = vma-\u003evm_mm;\n--\nmm/khugepaged.c-1603-\tif (result != SCAN_SUCCEED) {\nmm/khugepaged.c:1604:\t\tcc-\u003eprogress++;\nmm/khugepaged.c-1605-\t\tgoto out;\n--\nmm/khugepaged.c-1621-\tif (!pte) {\nmm/khugepaged.c:1622:\t\tcc-\u003eprogress++;\nmm/khugepaged.c-1623-\t\tresult = SCAN_NO_PTE_TABLE;\n--\nmm/khugepaged.c-1631-\nmm/khugepaged.c:1632:\t\tcc-\u003eprogress++;\nmm/khugepaged.c-1633-\n--\nmm/khugepaged.c-1685-\t\t */\nmm/khugepaged.c:1686:\t\tif (cc-\u003epolicy.anon_skip_lazyfree \u0026\u0026 !(vma-\u003evm_flags \u0026 VM_DROPPABLE) \u0026\u0026\nmm/khugepaged.c-1687-\t\t    folio_test_lazyfree(folio) \u0026\u0026 !pte_dirty(pteval)) {\n--\nmm/khugepaged.c-1713-\t\t/* The scan accepted this PTE as a collapse source */\nmm/khugepaged.c:1714:\t\t__set_bit(i, cc-\u003eeligible_ptes);\nmm/khugepaged.c-1715-\t\t/*\nmm/khugepaged.c-1716-\t\t * Record which node the original page is from and save this\nmm/khugepaged.c:1717:\t\t * information to cc-\u003enode_load[].\nmm/khugepaged.c-1718-\t\t * Khugepaged will allocate hugepage from the node has the max\n--\nmm/khugepaged.c-1726-\t\t}\nmm/khugepaged.c:1727:\t\tcc-\u003enode_load[node]++;\nmm/khugepaged.c-1728-\t\tif (!folio_test_lru(folio)) {\n--\nmm/khugepaged.c-1751-\nmm/khugepaged.c:1752:\t\tif (cc-\u003epolicy.anon_require_referenced \u0026\u0026\nmm/khugepaged.c-1753-\t\t    folio_pte_referenced(folio, vma, addr, pteval))\n--\nmm/khugepaged.c-1755-\t}\nmm/khugepaged.c:1756:\tif (cc-\u003epolicy.anon_require_referenced \u0026\u0026\nmm/khugepaged.c-1757-\t    (!referenced ||\n--\nmm/khugepaged.c-1765-\tif (result == SCAN_SUCCEED) {\nmm/khugepaged.c:1766:\t\tcc-\u003escan_orders = enabled_orders;\nmm/khugepaged.c:1767:\t\tcc-\u003escan_referenced = referenced;\nmm/khugepaged.c:1768:\t\tcc-\u003escan_unmapped = unmapped;\nmm/khugepaged.c-1769-\t}\n--\nmm/khugepaged.c=2229=static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,\n--\nmm/khugepaged.c-2617-\tretract_page_tables(mapping, start);\nmm/khugepaged.c:2618:\tif (cc-\u003epolicy.file_install_pmd)\nmm/khugepaged.c-2619-\t\tresult = SCAN_PTE_MAPPED_HUGEPAGE;\n--\nmm/khugepaged.c=2667=static enum scan_result collapse_scan_file(struct mm_struct *mm,\n--\nmm/khugepaged.c-2727-\t\t}\nmm/khugepaged.c:2728:\t\tcc-\u003enode_load[node]++;\nmm/khugepaged.c-2729-\n--\nmm/khugepaged.c-2760-\tif (result == SCAN_PTE_MAPPED_HUGEPAGE)\nmm/khugepaged.c:2761:\t\tcc-\u003eprogress++;\nmm/khugepaged.c-2762-\telse\nmm/khugepaged.c:2763:\t\tcc-\u003eprogress += HPAGE_PMD_NR;\nmm/khugepaged.c-2764-\n--\nmm/khugepaged.c=2775=static void collapse_control_init(struct collapse_control *cc)\nmm/khugepaged.c-2776-{\nmm/khugepaged.c:2777:\tcc-\u003eprogress = 0;\nmm/khugepaged.c:2778:\tcc-\u003escan_file = NULL;\nmm/khugepaged.c-2779-}\n--\nmm/khugepaged.c=2781=static enum scan_result collapse_scan_pmd(struct vm_area_struct *vma,\n--\nmm/khugepaged.c-2788-\t/* A scan that found work has to have been followed by collapse_pmd() */\nmm/khugepaged.c:2789:\tif (WARN_ON_ONCE(cc-\u003escan_file)) {\nmm/khugepaged.c:2790:\t\tfput(cc-\u003escan_file);\nmm/khugepaged.c:2791:\t\tcc-\u003escan_file = NULL;\nmm/khugepaged.c-2792-\t}\n--\nmm/khugepaged.c-2809-\t */\n\n"
}

49/3 2026/10/14 23:17 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 49242
							output: 37
							thoughts: 40
						

Thoughts:
Okay, let's dive into this. Here's how I'd approach that specific section of `mm/khugepaged.c` using my expertise:

**Examining `cc->` Usage in khugepaged.c**

Alright, the objective is to understand the context of `cc->` within the `mm/khugepaged.c` file. I need to refresh my memory on what `cc` actually refers to in that particular module. Given the file and the general context, it's likely related to the control structure or a data structure internal to the kernel's huge page management. The range specified, lines 2820 to 2860, suggests a function, a critical loop, or maybe the setup for a major operation, so let's zero in. I'm guessing that 'cc' is a control struct for a particular set of hugepages.

I would start by quickly scanning that section in the file. I'm looking for where `cc` is declared, how it's initialized, and, most importantly, the operations performed on its members. Are we talking about allocation, deallocation, page migration, locking, accounting, or something else? Understanding the context will tell me exactly what `cc` is about.

What members of the `cc` structure are being accessed? That's going to quickly reveal the function of this code. Are they being incremented, decremented, checked against some threshold, or used in function calls? Any conditionals involving `cc->` members will be particularly insightful.

I'd also keep an eye out for any interactions with other related data structures. Are there any references to page tables, virtual memory areas, or other kernel objects? Are there any locking mechanisms used in conjunction with `cc`? That's essential to understand the concurrency implications of this code.

Ultimately, I want to form a mental model of how `cc->` is used, and more broadly, how this code contributes to the overall function of khugepaged. Does this control access to a specific hugepage, a set of hugepages, or even a pool of hugepages? Is there a subtle performance optimization or a more fundamental feature being implemented here? This deeper understanding is what I'm aiming for.



50/3 2026/10/14 23:17 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 2820,
  "LineCount": 40
}

Results:
{
  "Contents": "2820:\t\tbool triggered_wb = false;\n2821:\t\tpgoff_t pgoff;\n2822:\t\n2823:\t\tif (!file)\n2824:\t\t\treturn collapse_anon(mm, addr, cc);\n2825:\t\n2826:\t\tcc-\u003escan_file = NULL;\n2827:\t\tpgoff = cc-\u003escan_pgoff;\n2828:\t\n2829:\t\t/* The scan found the PMD folio in place: nothing to collapse */\n2830:\t\tif (result == SCAN_PTE_MAPPED_HUGEPAGE)\n2831:\t\t\tgoto put;\n2832:\tretry:\n2833:\t\tresult = collapse_file(mm, addr, file, pgoff, cc);\n2834:\t\n2835:\t\t/* Dirty pages are worth a writeback and one more try, if asked for */\n2836:\t\tif (cc-\u003epolicy.file_writeback_dirty \u0026\u0026 result == SCAN_PAGE_DIRTY_OR_WRITEBACK \u0026\u0026\n2837:\t\t    !triggered_wb \u0026\u0026 mapping_can_writeback(file-\u003ef_mapping)) {\n2838:\t\t\tconst loff_t lstart = (loff_t)pgoff \u003c\u003c PAGE_SHIFT;\n2839:\t\t\tconst loff_t lend = lstart + HPAGE_PMD_SIZE - 1;\n2840:\t\n2841:\t\t\tfilemap_write_and_wait_range(file-\u003ef_mapping, lstart, lend);\n2842:\t\t\ttriggered_wb = true;\n2843:\t\t\tgoto retry;\n2844:\t\t}\n2845:\tput:\n2846:\t\tfput(file);\n2847:\t\n2848:\t\t/*\n2849:\t\t * A PMD folio is in the page cache, whether the collapse just put it\n2850:\t\t * there or found it: retract the PTE table, and map the PMD if asked.\n2851:\t\t */\n2852:\t\tif (result == SCAN_PTE_MAPPED_HUGEPAGE) {\n2853:\t\t\tmmap_read_lock(mm);\n2854:\t\t\tif (collapse_test_exit_or_disable(mm))\n2855:\t\t\t\tresult = SCAN_ANY_PROCESS;\n2856:\t\t\telse\n2857:\t\t\t\tresult = try_collapse_pte_mapped_thp(mm, addr,\n2858:\t\t\t\t\t\t\t\tcc-\u003epolicy.file_install_pmd);\n2859:\t\t\tif (result == SCAN_PMD_MAPPED)\n"
}

51/3 2026/10/14 23:17 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 50466
							output: 279
							thoughts: 1893
						

Thoughts:
**Analysis of Potential KMSAN Needs for Hugepage Collapse Refactoring**

Alright, let's dive into this patch. I see some refactoring in `cc->scan_file`, `cc->policy`, and other areas. The overall goal is to streamline the hugepage collapse logic, specifically by moving definitions, consolidating policy settings, and separating scan and collapse phases. My immediate thought is, what are the KMSAN implications? This is what I need to check.

First, I need to understand the commit's core purpose. The patch refactors hugepage collapse:
1.  Moves `enum scan_result`, `struct collapse_limits`, `struct collapse_policy`, and `struct collapse_control` into `mm/collapse.h`.
2.  Consolidates khugepaged/madvise collapse policy into `struct collapse_policy`.
3.  Separates scan from collapse phases, recording scan state in `collapse_control`.
4.  Updates `collapse_possible()` -> `collapse_possible_orders()`.
5.  Removes `mmgrab(mm)` and `mmdrop(mm)` in `madvise_collapse`.

Now I need to evaluate this against the KMSAN criteria.

*   **Criterion 1:** Are any kernel structures sent to userspace? No, `khugepaged.c` doesn't leak any structs to userspace. The sysfs interface takes input, and `madvise` is a syscall returning an int (error code), there are no `copy_to_user`, `put_user`, netlink, ioctl, etc.

*   **Criterion 2:** Any conditional logic dependent on potentially uninitialized variables? Let's check `struct collapse_control`:
    *   `policy`:  Initialized in `khugepaged_do_scan` and `madvise_collapse`. I can see all fields being initialized for both cases.
    *   `cc->progress`: Initialized to 0.
    *   `cc->scan_file`: Initialized to `NULL` and appropriately set.
    *   `cc->scan_pgoff`: Written alongside `cc->scan_file`.
    *   `cc->node_load`, `cc->alloc_nmask`, `cc->eligible_ptes`: Reset via `collapse_scan_reset(cc)`.
    *   `cc->scan_orders`, `cc->scan_referenced`, `cc->scan_unmapped`: Written appropriately. Note that `khugepaged_scan_mm_slot` receives `cc` initialized in `khugepaged_do_scan`.

    My analysis indicates that all fields are initialized before use in any of the relevant code paths.

*   **Criterion 3:**  Are any complex data structures allocated or initialized with uninitialized fields that could be read later? No, based on what I'm seeing, there's no evidence of this.

*   **Criterion 4:** Any bounds checks or logic that might allow access to uninitialized bytes? The code here deals with page table scanning, allocation and updating, so I need to make sure that there are no such bugs. This code is about allocating folios, copying page contents, and updating page tables.

I must also think about what types of bugs this refactoring *could* introduce: locking/refcounting issues (caught by LOCKDEP), use-after-free (KASAN), logic errors in THP handling (KASAN/assertions), and out-of-bounds PTE access (KASAN). But the important thing is, that none of them is related to uninitialized memory.

So, the key questions are: Is there any uninitialized memory read or info leak risk? No, I'm not seeing any. There are no info leaks, no user-facing buffers, no uninitialized struct reads, and no uninitialized variables used in branching.

Given the criteria and the nature of the patch, it seems very unlikely that KMSAN would find any new issues here. The potential risks are handled by KASAN, LOCKDEP or other means.

The instructions are clear. "THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN, LOCKDEP, OR OTHER STANDARD BUG DETECTORS." I'm confident in setting `NeedsKMSAN=false`.



52/3 2026/10/14 23:17 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch series refactors the transparent hugepage (THP) collapse logic in mm/khugepaged.c by introducing struct collapse_policy and struct collapse_control in mm/collapse.h to encapsulate collapse configurations (khugepaged vs madvise) and state across scan and collapse phases.\n\nEvaluating against KMSAN criteria:\n1. No kernel structures or data are copied to user space (no copy_to_user, put_user, netlink, ioctl output, socket options, or BPF buffers).\n2. All fields in struct collapse_policy and struct collapse_control are explicitly initialized (via collapse_control_init(), collapse_policy_khugepaged(), collapse_policy_madvise(), collapse_scan_reset(), and during successful scan phases) prior to being read or used in conditional logic.\n3. No uninitialized memory usage or info-leak risks are introduced. Any potential bugs in this refactoring would pertain to page/folio reference counting, locking (mmap_lock / folio locks), or state-tracking logic, which are covered by KASAN, LOCKDEP, and standard kernel debugging facilities.\n\nTherefore, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch series refactors the transparent hugepage (THP) collapse logic in mm/khugepaged.c by introducing struct collapse_policy and struct collapse_control in mm/collapse.h to encapsulate collapse configurations (khugepaged vs madvise) and state across scan and collapse phases.\n\nEvaluating against KMSAN criteria:\n1. No kernel structures or data are copied to user space (no copy_to_user, put_user, netlink, ioctl output, socket options, or BPF buffers).\n2. All fields in struct collapse_policy and struct collapse_control are explicitly initialized (via collapse_control_init(), collapse_policy_khugepaged(), collapse_policy_madvise(), collapse_scan_reset(), and during successful scan phases) prior to being read or used in conditional logic.\n3. No uninitialized memory usage or info-leak risks are introduced. Any potential bugs in this refactoring would pertain to page/folio reference counting, locking (mmap_lock / folio locks), or state-tracking logic, which are covered by KASAN, LOCKDEP, and standard kernel debugging facilities.\n\nTherefore, a dedicated KMSAN fuzzing session is not warranted.",
  "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)